答:
To be perfectly blunt, this sounds like a bad idea. This model mixes up some things which should stay separate.

From this spec, I see three data tables list, node, datum.

list

id

name

node

id

position_in_list

list_id

datum_id

datum

id

data_value_1

data_value_2

…

OK, so obviously you won't have a datum table, but it's a placeholder for your real data.

A list name 'foo' in the can then be reconstructed with:

```<code>SELECT datum.*
  FROM datum
  LEFT JOIN node ON datum.id = node.datum_id
  LEFT JOIN list ON node.list_id = list.id
WHERE list.name = 'foo'
  BY node.position_in_list
</code>```

Body:
This question branches out of this question, What are the differences between algorithms using data structures and algorithms using databases?.

The General Question

Should a database table(s) structure match its intended data structure(s) in the logic?

Some Context

The simplest example (and it may be oversimplified) of what I am thinking about is a database table whose columns match the properties of a linked list data structure.  So the properties I think of for a linked list are the following:

Linked List

Node identity.

Item/Content in node.

Next node.

In regards to the general question, the database table columns that I think of getting mapped are the following:

Linked List > Database Table

Node Identity > Primary Key Column(s).

Item/Content in node > Column(s) containing data that is to be persisted.

Next node > Column containing a reference to the record that is to follow it in the same table.

An application I can think of that represents the above is to say, keep track of a trail of points you have been to on a map.  So I can imagine saving the coordinates of point A then putting in the mapped Next node column, the coordinates of point B.  Letting my imagination run a little further, then retrieve this data and load it into a linked list, use its properties to do the traversal, and draw these points on a map again at a later point in time.

Questions

I can see how creating a mapping like this simplifies thinking about the data, but I also feel it restricts you to thinking about the data in only this way.  How conforming do you make your database tables to data structure(s), if at all?

Should databases be viewed as realms of raw data that are to be shaped and molded (translated) to data structures selected dependent on the program's purpose?

I restate what I said in the last post.  I know answers without a specific context are difficult.  Food-for-thought, advice, or discussion points are mainly what I'm looking for and would be most appreciated!  I did try to give a more specific context in this post.

Body:
To be perfectly blunt, this sounds like a bad idea. This model mixes up some things which should stay separate.

From this spec, I see three data tables list, node, datum.

list

id

name

node

id

position_in_list

list_id

datum_id

datum

id

data_value_1

data_value_2

…

OK, so obviously you won't have a datum table, but it's a placeholder for your real data.

A list name 'foo' in the can then be reconstructed with:

SELECT datum.*
  FROM datum
  LEFT JOIN node ON datum.id = node.datum_id
  LEFT JOIN list ON node.list_id = list.id
WHERE list.name = 'foo'
  BY node.position_in_list


问:
Should a database table(s) structure match its intended data structure(s) in the logic?
This question branches out of this question, What are the differences between algorithms using data structures and algorithms using databases?.

The General Question

Should a database table(s) structure match its intended data structure(s) in the logic?

Some Context

The simplest example (and it may be oversimplified) of what I am thinking about is a database table whose columns match the properties of a linked list data structure.  So the properties I think of for a linked list are the following:

Linked List

Node identity.

Item/Content in node.

Next node.

In regards to the general question, the database table columns that I think of getting mapped are the following:

Linked List > Database Table

Node Identity > Primary Key Column(s).

Item/Content in node > Column(s) containing data that is to be persisted.

Next node > Column containing a reference to the record that is to follow it in the same table.

An application I can think of that represents the above is to say, keep track of a trail of points you have been to on a map.  So I can imagine saving the coordinates of point A then putting in the mapped Next node column, the coordinates of point B.  Letting my imagination run a little further, then retrieve this data and load it into a linked list, use its properties to do the traversal, and draw these points on a map again at a later point in time.

Questions

I can see how creating a mapping like this simplifies thinking about the data, but I also feel it restricts you to thinking about the data in only this way.  How conforming do you make your database tables to data structure(s), if at all?

Should databases be viewed as realms of raw data that are to be shaped and molded (translated) to data structures selected dependent on the program's purpose?

I restate what I said in the last post.  I know answers without a specific context are difficult.  Food-for-thought, advice, or discussion points are mainly what I'm looking for and would be most appreciated!  I did try to give a more specific context in this post.

答:
Specifically for the linked list situation: in SQL-databases it is usually far easier to store an 'ordering' field (numerical) which is renumbered if you ever want to insert or remove a node: even updating a large number of columns (ordering = ordering+1) is usually fast. Navigating a list of linked nodes is very unpractical, since you can't do it with a simple query.  </p>

<p>This in itself is a perfect example why datastructures and implementation don't always map well to each other. </p>

ContentLicense: CC BY-SA 3.0

Body:
Specifically for the linked list situation: in SQL-databases it is usually far easier to store an 'ordering' field (numerical) which is renumbered if you ever want to insert or remove a node: even updating a large number of columns (ordering = ordering+1) is usually fast. Navigating a list of linked nodes is very unpractical, since you can't do it with a simple query.

This in itself is a perfect example why datastructures and implementation don't always map well to each other.


问:
What does it mean to expose a C++ code publicly as a C API and what are the advantages of doing it?
I often hear people say that C++ programmers should expose their library's/product's public API as a C API.

What does that mean and what are the advantages of that?

答:
It does mean that the part of your library that is exposed as an interface only uses the C "part" of the language, so you're not exporting classes or similar, only functions, PODs and structs containing PODs. Plus, you have to disable the C++ name mangling, usually achieved by marking functions as extern "C". A typical example would be:

```<code>extern "C" void foo(int bar);
</code>```

The big advantage of exposing your libraries in this fashion is that pretty much every programming language out there has a mechanism to directly interface with a C library, but only very few can also interface directly with a C++ library. So in that sense, you go for the lowest common denominator to make it easy for other people to use your library.

However keep in mind that this is really only a useful strategy if you are producing a library for other people to consume. If you are building a piece of C++-only software and the libraries only need to interface with each other, you are (IMHO) better off exposing proper C++ APIs so you can make use of the full power of the language.

Body:
It does mean that the part of your library that is exposed as an interface only uses the C "part" of the language, so you're not exporting classes or similar, only functions, PODs and structs containing PODs. Plus, you have to disable the C++ name mangling, usually achieved by marking functions as extern "C". A typical example would be:

extern "C" void foo(int bar);

The big advantage of exposing your libraries in this fashion is that pretty much every programming language out there has a mechanism to directly interface with a C library, but only very few can also interface directly with a C++ library. So in that sense, you go for the lowest common denominator to make it easy for other people to use your library.

However keep in mind that this is really only a useful strategy if you are producing a library for other people to consume. If you are building a piece of C++-only software and the libraries only need to interface with each other, you are (IMHO) better off exposing proper C++ APIs so you can make use of the full power of the language.


问:
Represent actions(verbs) in REST URI
I have a print operation to perform for my customer documents.
I need the other standard operations to be performed as well, like add,update, delete.
so, I have following:

For creating new customer:
URI = /customer/{id}, type = POST,
Methodname = CreateCustomer()

For updating:
URI: /customer/{id}, type = PUT, method =
UpdateCstomer()

For Delete customer:
URI = /customer/{id}, type =
DELETE, Methodname = DeleteCustomer()

For View:
URI: /customer/{id}, type = GET, method = GetCustomer()

Now, if I need to print a document for that customer, I need a print function.
My URI may look like this: /customer/{id}, type = POST , method = PrintCustomer().
But I have used that URI and POST type for CreateCustomer.
I wanted the URI to look like this:
/customer/Print/{id}, type = POST , method = PrintCustomer().

But I cannot have "Print" verb in my URI. Whats the best way to do this?
I thought about /customer/document/{id} as the URI... but I will run into the same issue.
I would have the CRUD operations on the "document". So, again I run out of what I would used for "print".
Please advise.

答:
Just add a parameter to the current URI's GET

It's pretty typical to use a URI's for multiple actions.

If you're talking about the same resource but a different action, you'd define it as a parameter.

/customer/{id}?print=true

Then where you define your GET method you detect the presence of the print parameter and handle it differently.

REST is defined in the following way:

POST - Create a record, asset, or resource

PUT - Update, a record, asset, or resource

DELETE - Remove a, record, asset, or resource

GET, on the other hand, is meant to be used in multiple ways because there are typically a lot of different forms that a resource may be retrieved. That's also why GET requests are represented as a query string. If you were working with a database resource you'd literally be retrieving a view via a query but REST is intentionally abstracted to a higher level because it's designed to handle with many different types of resources.

The REST specification is pretty forward thinking, even though API's are only recently starting to use it heavily.

If you're interested in learning more about REST protocols I highly suggest you read "Haters Gonna Hate HATEOAS".

Update:

@Shauna pointed out an interesting hole in my reasoning. There's no true right way and many forms are considered acceptable. I thought about it some more and since your intended use is to transform the data into a different representation, it makes sense to define the transform as a new MIME-Type.

For example, you could represent the URI as:

```<code>/customer/{id}+print
</code>```

Where you could set the response Content-Type to text/html+print. That way you'd also have the option to define more transforms in the future.

For example:

```<code>// for application/json
/customer/{id}+json

// for application/atom+xml
/customer/{id}+atom
</code>```

Either way, all forms are acceptable. The implementation you decide depends more on personal preference, and the capabilities of your server.

Aside: Let me clarify since there seems to be some confusion. The 'print' query-parameter and/or content-type is used to specify how the resource is transformed. Not how to trigger a physical print job. For security reasons, hardware-level access is always left to the user/client/browser.

Title: Represent actions(verbs) in REST URI

Body:
Just add a parameter to the current URI's GET

It's pretty typical to use a URI's for multiple actions.

If you're talking about the same resource but a different action, you'd define it as a parameter.

/customer/{id}?print=true

Then where you define your GET method you detect the presence of the print parameter and handle it differently.

REST is defined in the following way:

POST - Create a record, asset, or resource

PUT - Update, a record, asset, or resource

DELETE - Remove a, record, asset, or resource

GET, on the other hand, is meant to be used in multiple ways because there are typically a lot of different forms that a resource may be retrieved. That's also why GET requests are represented as a query string. If you were working with a database resource you'd literally be retrieving a view via a query but REST is intentionally abstracted to a higher level because it's designed to handle with many different types of resources.

The REST specification is pretty forward thinking, even though API's are only recently starting to use it heavily.

If you're interested in learning more about REST protocols I highly suggest you read "Haters Gonna Hate HATEOAS".

Update:

@Shauna pointed out an interesting hole in my reasoning. There's no true right way and many forms are considered acceptable. I thought about it some more and since your intended use is to transform the data into a different representation, it makes sense to define the transform as a new MIME-Type.

For example, you could represent the URI as:

/customer/{id}+print

Where you could set the response Content-Type to text/html+print. That way you'd also have the option to define more transforms in the future.

For example:

// for application/json
/customer/{id}+json

// for application/atom+xml
/customer/{id}+atom

Either way, all forms are acceptable. The implementation you decide depends more on personal preference, and the capabilities of your server.

Aside: Let me clarify since there seems to be some confusion. The 'print' query-parameter and/or content-type is used to specify how the resource is transformed. Not how to trigger a physical print job. For security reasons, hardware-level access is always left to the user/client/browser.


问:
Should the methods of a class call its own getters and setters?
Where I work I see lots of classes that do things like this:

```<code>public class ClassThatCallsItsOwnGettersAndSetters {

    private String field;

    public String getField() {
        return field;
    }

    public void setField(String field) {
        this.field = field;
    }

    public void methodWithLogic() {
        setField("value");
        //do stuff
        String localField = getField();
        //do stuff with "localField"
    }
}
</code>```

If I wrote this from scratch, I would have written the methodWithLogic() like this instead:

```<code>public class ClassThatUsesItsOwnFields {

    private String field;

    public String getField() {
        return field;
    }

    public void setField(String field) {
        this.field = field;
    }

    public void methodWithLogic() {
        field = "value";
        //do stuff
        //do stuff with "field"
    }
}
</code>```

I feel that when the class calls its own getters and setters, it makes the code harder to read.  To me it almost implies that complex logic is happening in that method call even though in our case it almost never is.  When I'm debugging some unfamiliar code, who's to say that the bug isn't some side effect in that method?  In other words, it makes me take lots of side trips on the journey of understanding the code.

Are there benefits to the first method? Is the first method actually better?

答: Yes, the methods of your class should call the getters and setters. The whole point in writing getters and setters is future proofing. You could make every property a field and directly expose the data to the users of the class. The reason you build the getters and setters isn't necessarily because there is complex logic now but so that the interface doesn't break in the future if you have to add it.</p>


答:
I won't say which is better or worse, because that partly depends on your situation (in my opinion).  But consider that your getters and setters may change implementation later, and bypassing them would skip that logic.

For example, what happens if you add a "dirty" flag to some setter fields later?  By calling your setters in your internal code you'll set the dirty flag without changing any other code.  In many situations this would be a good thing.

Title: Should the methods of a class call its own getters and setters?

Body:
Where I work I see lots of classes that do things like this:

```<code>public class ClassThatCallsItsOwnGettersAndSetters {

    private String field;

    public String getField() {
        return field;
    }

    public void setField(String field) {
        this.field = field;
    }

    public void methodWithLogic() {
        setField("value");
        //do stuff
        String localField = getField();
        //do stuff with "localField"
    }
}
</code>```

If I wrote this from scratch, I would have written the methodWithLogic() like this instead:

```<code>public class ClassThatUsesItsOwnFields {

    private String field;

    public String getField() {
        return field;
    }

    public void setField(String field) {
        this.field = field;
    }

    public void methodWithLogic() {
        field = "value";
        //do stuff
        //do stuff with "field"
    }
}
</code>```

I feel that when the class calls its own getters and setters, it makes the code harder to read.  To me it almost implies that complex logic is happening in that method call even though in our case it almost never is.  When I'm debugging some unfamiliar code, who's to say that the bug isn't some side effect in that method?  In other words, it makes me take lots of side trips on the journey of understanding the code.

Are there benefits to the first method? Is the first method actually better?


答:
If you are trying to accomplish something that is provided by the public interface, then use the getters/setters.

However, as the owner/developer of the class, you are allowed to access the private sections of your code (from within the class of course), but you are also responsible for mitigating the dangers.

So maybe you have a getter that iterates over some internal list, and you want to get the current value without incrementing the iterator. In this case, use the private variable.

```<code>public class MyClass
{
    private int i;
    private List<string> list;
    public string getNextString()
    {
        i++;
        return list[i];
    }

    private void getString()
    {
        // Do not increment
        string currentString = list[i];

        // Increment
        string nextString = getNextString();
    }
}
</code>```

Body:
If you are trying to accomplish something that is provided by the public interface, then use the getters/setters.

However, as the owner/developer of the class, you are allowed to access the private sections of your code (from within the class of course), but you are also responsible for mitigating the dangers.

So maybe you have a getter that iterates over some internal list, and you want to get the current value without incrementing the iterator. In this case, use the private variable.

public class MyClass
{
    private int i;
    private List<string> list;
    public string getNextString()
    {
        i++;
        return list[i];
    }

    private void getString()
    {
        // Do not increment
        string currentString = list[i];

        // Increment
        string nextString = getNextString();
    }
}


答:
Calling the setter directly is not, in and of itself, a problem. The question really should be: Why does our code have setters everywhere?

Mutable classes are a dangerous game, particularly where the class itself manages its own state. Consider how many of those setters truly need to exist. How many could be set in the constructor and then become encapsulated entirely by the class itself?

If the field must be settable externally then ask yourself if the method with logic should be there. Is your class itself really just a data/state class? Does this class have more than one responsibility?

Don't get me wrong, there will be cases where this is fine. I'm not saying that you should eliminate setters on classes with logic entirely. But these should be the exception, not the rule. And, in those few cases, it should be obvious which to access directly.


问:
Default vs Impl when implementing interfaces in Java
After reading Should package names be singular or plural? it occurred to me that I've never seen a proper debate covering one of my pet peeves: naming implementations of interfaces.

Let's assume that you have a interface Order that is intended to be implemented in a variety of ways but there is only the initial implementation when the project is first created. Do you go for DefaultOrder or OrderImpl or some other variant to avoid the false dichotomy? And what do you do when more implementations come along?

And most important... why?

答:
I agree with Nicole's answer (particularly that the interface probably isn't necessary in most cases), but for the sake of discussion I'll throw out an additional alternative other than OrderImpl and DefaultOrder: hide the implementation behind a static factory method like Orders.create(). For example:

```<code>public final class Orders {
  public static Order create() {
    return new Order() {
      // Implementation goes here.
    };
  }
}
</code>```

With this approach, the implementation could be an anonymous inner class, or it could be a private class with Default or Impl in the name, or it could be named something else entirely. Which ever choice is made, the caller doesn't need to care, so you get more flexibility now and later on when/if you decide to change it.

Some great examples of this pattern in practice are the java.util.Collections and java.util.concurrent.Executors utility classes, whose methods return hidden implementations. As Effective Java mentions (in Item 1), this pattern can help keep the "Conceptual weight" of the API smaller.

Body:
I agree with Nicole's answer (particularly that the interface probably isn't necessary in most cases), but for the sake of discussion I'll throw out an additional alternative other than OrderImpl and DefaultOrder: hide the implementation behind a static factory method like Orders.create(). For example:

public final class Orders {
  public static Order create() {
    return new Order() {
      // Implementation goes here.
    };
  }
}

With this approach, the implementation could be an anonymous inner class, or it could be a private class with Default or Impl in the name, or it could be named something else entirely. Which ever choice is made, the caller doesn't need to care, so you get more flexibility now and later on when/if you decide to change it.

Some great examples of this pattern in practice are the java.util.Collections and java.util.concurrent.Executors utility classes, whose methods return hidden implementations. As Effective Java mentions (in Item 1), this pattern can help keep the "Conceptual weight" of the API smaller.

ContentLicense: CC BY-SA 4.0


问:
Is it possible to read memory from another program by allocating all the empty space on a system?
Theoretically, if I were to build a program that allocated all the unused memory on a system, and continued to request more and more memory as other applications released memory that they no longer need, would it be possible to read recently released memory from another applications? Or is this somehow protected by modern operating system?

I have no practical application for this, I'm just curious. I realize there are some issues with allocating "all available memory" in real-life.

Edit: To clarify, I'm asking specifically about "Released" memory, not accessing memory that is currently allocated by another application.

答:
No, this won't allow another program to read another's memory thanks to the magic of paging. This way, total memory use can exceed the physical ram by offloading parts of it to the harddrive.

Also, the maximum memory a process can allocate is arbitrarily limited by the OS (up to 4 gigs for a 32 bit architecture)  after which the next alloc call will return an out of memory error.


答:
As a database person I want to throw up at the idea of someone designing a database table that way.

Database tables should be designed using three main criteria:

Data integrity

Performance of querying the database

Data security

A good database design often needs fields that are not used by the application in any way (but may be needed for data imports or auditing or for some other reason) and in many databases, multiple applications will need to access the data and have differing needs.

What looks easy to do for data entry screens may not work at all for reporting (which is often a totally different application that the developer designing only for his logic doesn't even know about) because reports tend to deal with larger data sets than data entry screens which typically only concern one record at a time. So a database struture that looks logical from the application programmers perspective (Like an EAV table, shudder!) can be the worst possible thing to use when getting data back out of the database later.  Especially if there will be millions of records.

Databases are optimized to use normalized tables and should be designed with normalization priciples in mind not using Object-oriented principles. Yes there is mismatch between what is best for the database and what is best for an object-oriented application. Yes you have to deal with that and no it isn't a good idea to deal with it by making the database match the orject-orientation.

Title: Should a database table(s) structure match its intended data structure(s) in the logic?


问:
What are some famous one-liner or two-liner programs and equations?
I'm experimenting with a new platform and I'm trying to write a program that deals with strings that are no longer than 60 characters and I'd like to populate the data store with some famous or well-known small chunks of code and equations, since programming and math goes along with the theme of my software. The code can be in any language and the equations from any discipline of mathematics, just so long as they're less than a total of 60 characters in length. I suspect people are gonna break out some brainfuck for this one.

For example,

```<code>#include<stdio.h>
int main(){printf ("Hi World\n");return 0;}
</code>```

60 characters exactly!

Thanks so much for your wisdom!

答:
import this in Python.

EDIT as comments cannot contain line breaks:  For those without a Python interpreter handy, this is the output

```<code>Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
</code>```

ContentLicense: CC BY-SA 2.5

Body:
import this in Python.

EDIT as comments cannot contain line breaks:  For those without a Python interpreter handy, this is the output

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!


答: Yes, it's theoretically possible to read another process' released memory.  It was the source of a number of privilege escalation attacks back in the day.  Because of that, operating systems nowadays effectively zero out memory if it was previously allocated by another process.  The reason you don't always see zeroed out memory is because it is more efficient not to zero out the memory if it was previously allocated by the same process.  The OS tries to give back memory pages to the same process if it can.</p>

Title: Is it possible to read memory from another program by allocating all the empty space on a system?

Body:
Theoretically, if I were to build a program that allocated all the unused memory on a system, and continued to request more and more memory as other applications released memory that they no longer need, would it be possible to read recently released memory from another applications? Or is this somehow protected by modern operating system?

I have no practical application for this, I'm just curious. I realize there are some issues with allocating "all available memory" in real-life.

Edit: To clarify, I'm asking specifically about "Released" memory, not accessing memory that is currently allocated by another application.


答:
No, because a good kernel wipes the contents of memory before it is issued to a process to protect against exactly the kind of attack you propose.

On Unixy systems, memory is allocated to processes by extending what's called the program break, which is the limit of virtually-addressable space a process can use.  A process tells the kernel it wants to extend its addressable space, and the kernel will allow it if memory is available or the call will fail if not.  (The name of the brk() system call comes from this concept.)

In practice, large blocks of freed memory don't often butt up against the program break, which is what would be required for a process to return memory to the kernel by shrinking the program break.  This is, of course, all dependent on your system's implementation of malloc() and free().  If you have sources available, they'll tell you whether or not memory is ever returned.

There are no security implications for malloc() not initializing memory because anything it got via brk() will have been scrubbed and anything previously free()d will have been written by the same process.


问:
Method vs Function vs Procedure
Simple question, but I often hear these three terms defined with such ferocity, but which have been known to me to mean different things over the years.

What are the "correct" definitions of "Procedures", "Methods", "Function", "Subroutines", etc?

答:
80% of proficiency is directly related to familiarity with nomenclature,

95% of productivity is the ability to identify what is useful at the moment despite the terms used to describe it

I pretty much prefer to call them all methods in c# except back when I used MSSQL we had sproc's, but of course now we use Postgres and they are called functions.

Title: Method vs Function vs Procedure


问:
For PL/SQL, do large companies prefer ANSI SQL joins or old Oracle joins?
I am interviewing for a PL/SQL position with a large corporation. I will have to write a multiple choice exam. I am wondering whether the exam will likely use old-style joins (joining happens in the 'WHERE' clause) or ANSI ones. My apologies if this is not the correct forum for this question.</p>

答:
Show them you know both styles.

I can tell you by experience that PL/SQL programmers prefer the Oracle-style joins.

I have maintained PL/SQL solution and hardly ever seen an ANSI-join.

Left and right joins and more terse because of the (+) especial Oracle keyword.

Been said that, ANSI-joins are more universal and make it easier to migrate between different RDBMS.

It's probable that your interviewer, if he/she is an Oracle lifelong programmer, is unfamiliar with the ANSI-style.

I tend to think that if you are looking for an PL/SQL position, do things the Oracle way. That's what they would expect.


答:
In addition to Timo's answer - there is no standarised C++ ABI for some platforms (for example Windows - some like Linux of Mac OS X widely adopted) so it is not only matter of missing feature but impossibility of implementing such feature.

For example IIRC MSVC have different ABI in each version and it might change depending whether it is debug or release build - and it is not published so 3rd party compilers are usually not compatible (I read some information that some version of icc is compatible with MSVC 2005 but it might be information disclosed under NDA - not necessary available to creators of say Python) and use their own ABI. So in practice language environment would limit not only the compiler version but also flags.

Finally C++ have much more compile-time features. For example generics usually don't exists in the dynamically typed languages etc.

Title: What does it mean to expose a C++ code publicly as a C API and what are the advantages of doing it?

Body:
I often hear people say that C++ programmers should expose their library's/product's public API as a C API.

What does that mean and what are the advantages of that?


答:
Short answer: NO

Longer answer:

A single database can be used my many applications, and one application can use many databases.

Also: program against views, not against tables.


答: I had a good one and I wrote it down in the margin.</p>

Title: What are some famous one-liner or two-liner programs and equations?

Body:
I'm experimenting with a new platform and I'm trying to write a program that deals with strings that are no longer than 60 characters and I'd like to populate the data store with some famous or well-known small chunks of code and equations, since programming and math goes along with the theme of my software. The code can be in any language and the equations from any discipline of mathematics, just so long as they're less than a total of 60 characters in length. I suspect people are gonna break out some brainfuck for this one.

For example,

```<code>#include<stdio.h>
int main(){printf ("Hi World\n");return 0;}
</code>```

60 characters exactly!

Thanks so much for your wisdom!


问:
Feature organization / authentication?
Let's say I have a product that has different features, or different feature access depending on things (i.e Premium User, Beta, Demo, Logged-in User, etc..).

What's the best way to organize a system to where it's not a set of static checks (i.e a bunch of if statements, for example)?

The platform isn't important, I'm precisely asking for design principles / general design.

答:
A good example of this setup would be an Access Control List (ACL). Zend Framework (http://framework.zend.com/manual/2.0/en/modules/zend.permissions.acl.intro.html) has a permissions component implementing this type of setup. The general breakdown is that some models implement a Role interface and other models implement a Resource interface. A list (using a Registry pattern either through file configuration or in code) is created defining whether a Role can access a Resource and has a specific Privilege. I like to think of the privileges as an action list. There's lots to explore in that component.

```<code><?php
    //$acl has been previously defined and loaded
    echo $acl->isAllowed('someUser', 'someResource', 'somePrivilege') ? 'yup' : 'nope'; ?>

    //$user is currently not logged in and has a 'guest' role
    if ($acl->isAllowed($user->getRole(), 'paidArticles', 'view') {
        //Show the paid articles, secrets and all that
    } else {
        //Only show free articles
    }
    if ($acl->isAllowed($admin->getRole(), 'userList', 'delete') {
        //Allow $admin to delete users from the list
    } else {
        //Perhaps log that someone is trying to access something they shouldn't
    }
?>
</code>```

While I realize this is, or could turn into a complex set of If-Thens, at some point you'll have to have a method to say, "If access is allowed, Then show X content/widget/etc". If the permissions are fairly straightforward, it should remain simple. I think the main advantage here is it allows for a pretty basic isAllowed() and gives you a true/false based on however you have the roles, resources and actions setup. Past that it's very flexible as to what you do as you query the ACL.

Title: Feature organization / authentication?

Body:
A good example of this setup would be an Access Control List (ACL). Zend Framework (http://framework.zend.com/manual/2.0/en/modules/zend.permissions.acl.intro.html) has a permissions component implementing this type of setup. The general breakdown is that some models implement a Role interface and other models implement a Resource interface. A list (using a Registry pattern either through file configuration or in code) is created defining whether a Role can access a Resource and has a specific Privilege. I like to think of the privileges as an action list. There's lots to explore in that component.

<?php
    //$acl has been previously defined and loaded
    echo $acl->isAllowed('someUser', 'someResource', 'somePrivilege') ? 'yup' : 'nope'; ?>

    //$user is currently not logged in and has a 'guest' role
    if ($acl->isAllowed($user->getRole(), 'paidArticles', 'view') {
        //Show the paid articles, secrets and all that
    } else {
        //Only show free articles
    }
    if ($acl->isAllowed($admin->getRole(), 'userList', 'delete') {
        //Allow $admin to delete users from the list
    } else {
        //Perhaps log that someone is trying to access something they shouldn't
    }
?>

While I realize this is, or could turn into a complex set of If-Thens, at some point you'll have to have a method to say, "If access is allowed, Then show X content/widget/etc". If the permissions are fairly straightforward, it should remain simple. I think the main advantage here is it allows for a pretty basic isAllowed() and gives you a true/false based on however you have the roles, resources and actions setup. Past that it's very flexible as to what you do as you query the ACL.


问:
Good design pattern for a c++ wrapper around a c object
I have written an extensible c++ wrapper around a very hard to use but also very useful c library. The goal is to have the convience of c++ for allocating the object, exposing its properties, deallocating the object, copy semantics etc...

The problem is this: sometimes the c library wants the underlying object (a pointer to the object), and the class destructor should not destroy the underlying memory. While most of the time, the destructor should deallocate the underlying object. I have experimented with setting a bool hasOwnership flag in the class so that the destructor, assignment operator, etc... will know whether or not it should free the underlying memory or not. However, this is cumbersome for the user, and also, sometimes there is no way to know when another process will be using that memory.

Currently, I have it setup where when the assignment comes from a pointer of the same type as the underlying type, then I set the hasOwnership flag. I do the same when the overloaded constructor is called using the pointer from the c library. Yet, this still does not handle the case when the user has created the object and passed it to one of my functions which calls the c_api and the library stores the pointer for later use. If they were to delete their object, then it would no doubt cause a segfault in the c library.

Is there a design pattern that would simplify this process? Maybe some sort of reference counting?

答: There is a straightforward answer to your issue, smart pointers.  By using a smart pointer to hold the C library's memory and adding a reference when the pointer is also in the library (and dropping the reference when the C library returns) then you will automatically free the memory when the reference count drops to zero (and only then)</p>


问:
Generate commercial license key for web service

Background

I have a business question regarding web-based software licensing. A number of web sites offer software as a service for various APIs. A good example is Google's Custom Search API. The process to use web services typically resembles:

Account. User creates an account.

Server. User defines the IP address(es) of the server(s) that will make API requests.

Key. User receives a public API key for the desired API(s).

Guide. User is given documentation that shows how to use the API key to make a request.

Test. User can make test requests to verify integration functionality.

Billing. User pays to activate the account.

Production. User integrates the web service into their applications.

Deactivation. System deactivates accounts when expired, exceeds request limit, etc.

These requirements are in addition to integration with the service being licensed.

Problem

That is a lot of work for a small business.

Questions

What off-the-shelf, open source projects address this problem?

If there are no such projects, what would you do to architect a viable, low-cost solution (ideally, a percentage of each license)? That is, what software or existing commercial services would you use for a small business (having little to no income) that seeks to license web-based services?

Thank you!

Related Links

License key solution in web application, what is the best approach?

API Management System

答:
This problem is called API Management and there are a number of solutions.

Integrated Billing - FOSS

Solutions that offer integrated billing that are Open Source, free, or charge a percentage (based on subscriptions, so no up-front fees):

WSO2 API Manager

3Scale

Apigee and Apigee To-Go

Integrated Billing - Commercial

Solutions that offer integrated billing, but charge for services:

Agilis Software

Mashery (Partner, API) - Was $499/month; prices are now unlisted

WebServius

mashape - 20% of earnings; custom prices may be possible

apiary.io - in beta

SOA Software Open

Cloud Security Platform

Vordel API Server

SDK Bridge

Components

Various sites and software that offer partial solutions from which a complete solution can be created.

API Management

API Axle

Varnish API Key

apiGrove

Accounts

DailyCred - for accounts

Documentation

SaaS Pose - for API documentation

Billing

Stripe

FastSpring


问:
Is it necessary to add the default case while using switch cases?
During a recent code review I was asked to put default cases in all the files wherever switch block is used, even if there is nothing to do in default. That means I have to put the default case and write nothing in it.

Is this the right thing to do?
What purpose would it serve?

答:
Consider

```<code>enum Gender
{
       MALE ,
       FEMALE ;
}
</code>```

and

```<code>void run ( Gender g )
{
      switch ( g )
      {
           case MALE :
                 // code related to males
                 break ;
           default :
                 assert Gender . FEMALE . equals ( g ) ;
                 // code related to females
                 break ;
      }
}
</code>```

I would argue that this is superior to having a MALE case, a FEMALE case, and a default case that throws an exception.

During your testing phase, the computer will check if g is FEMALE.  During production, the check will be omitted.  (Yeah a microoptimization!)

More importantly, you will maintain your goal of 100% code coverage.  If you wrote a default case that throws an Exception, how would you ever test it?

Body:
Consider

enum Gender
{
       MALE ,
       FEMALE ;
}

and

void run ( Gender g )
{
      switch ( g )
      {
           case MALE :
                 // code related to males
                 break ;
           default :
                 assert Gender . FEMALE . equals ( g ) ;
                 // code related to females
                 break ;
      }
}

I would argue that this is superior to having a MALE case, a FEMALE case, and a default case that throws an exception.

During your testing phase, the computer will check if g is FEMALE.  During production, the check will be omitted.  (Yeah a microoptimization!)

More importantly, you will maintain your goal of 100% code coverage.  If you wrote a default case that throws an Exception, how would you ever test it?


问:
What's the career path for a developer who doesn't like management?
If you're developer (Senior or Lead Developer) and you'd rather stay with code/design than pursue a management career, what are the available career paths at your company, or any you've heard of? How far can you go?

Is it possible to continue being a geek until you bite the dust or is that too naive?

Are people like Uncle Bob for example still considered developers, as they claim?

答:
there are many titles that are found in a programmers path if he stick to technical career, such as

Lead Developer / Lead Development Engineer.

Team Leader.

Solution Architect (focused on system design and integration, etc.).

CTO (Chief technology Officer) .. this is totally technical but with a spice of being top technical person in the Organization.

OwnerDisplayName: Bishoy Ghaly


问:
Is a degree needed for low-level/embedded programming jobs?
I know that it is possible to get into software development without a degree in computer science, but is it possible (or rather, common) to be able to get an embedded programming job without the computer science degree (or any engineering degree as well)?</p>

答:
Some background in electronics (or at least a desire to get into it) is pretty much needed to be successful in embedded programming.  I've been doing this for 30+ years, and did the formal way (BSEE + MSCS), but I've run across a lot of good self-taught embedded programmers along the way.  They all had one thing in common though -- somewhere in their background they had some electronics education (formal or otherwise).

You're going to be doing a lot of bit twiddling and working with lots of low-level I/O registers, with so-called datasheets that might run several hundred pages, like this one (so if that document doesn't look interesting, forget about embedded programming).  You'll be using lots of serial busses like UART, SPI, I2C, and USB.  Eight and 16-bit timers.   Lots of interrupts.

You don't have to be able to design a circuit, but it's best if you learn to read a schematic since you will probably be probing a circuit board with an oscilloscope or logic analyzer.

Assuming you're working with medium-sized devices, that might have only 32K to 256K of program memory, and 4K-16K of RAM, you'll probably be doing most of your programming in C -- but C with proprietary extensions (different for each chip), because most of these processors are Harvard architecture and have separate address spaces for fast RAM, extended RAM, and code space and pointers can get really complicated.

(I consider small micros to be ones with just a few K of program memory and a few hundred bytes of RAM.  Those are still mostly programmed in assembly.  Then there are larger microprocessors that can run Linux and have MB of flash and RAM, but that's not really where main-stream embedded programming is either.)


答:
Often you can use a pattern like this:

```<code>class C {
public:
  void foo() {
    underlying_foo(handle.get());
  }

  void bar() {
    // transfers ownership
    underlying_bar(handle.release());
  }

  // use default copy/move constructor and assignment operator

private:
  struct deleter {
    void operator()(T* ptr) {
      deleter_fn(ptr);
    }
  };
  std::unique_ptr<T, deleter> handle;
};
</code>```

By using release you can explicitly transfer ownership. However this is confusing and you should avoid it if at all possible.

Most C libraries have a C++-like object life cycle (object allocation, accessors, destruction) that maps nicely onto the C++ pattern without ownership transfer.

If users need shared ownership, they should use shared_ptr with your classes. Don't try to implement any ownership sharing yourself.

Update: If you want to make the transfer of ownership more explicit, you can use a reference qualifier:

```<code>void bar() && { ... }
</code>```

Then users must call bar on lvalues like this:

```<code>C o;
std::move(o).bar();  // transfer of ownership is explicit at call site
</code>```

Title: Good design pattern for a c++ wrapper around a c object

Body:
I have written an extensible c++ wrapper around a very hard to use but also very useful c library. The goal is to have the convience of c++ for allocating the object, exposing its properties, deallocating the object, copy semantics etc...

The problem is this: sometimes the c library wants the underlying object (a pointer to the object), and the class destructor should not destroy the underlying memory. While most of the time, the destructor should deallocate the underlying object. I have experimented with setting a bool hasOwnership flag in the class so that the destructor, assignment operator, etc... will know whether or not it should free the underlying memory or not. However, this is cumbersome for the user, and also, sometimes there is no way to know when another process will be using that memory.

Currently, I have it setup where when the assignment comes from a pointer of the same type as the underlying type, then I set the hasOwnership flag. I do the same when the overloaded constructor is called using the pointer from the c library. Yet, this still does not handle the case when the user has created the object and passed it to one of my functions which calls the c_api and the library stores the pointer for later use. If they were to delete their object, then it would no doubt cause a segfault in the c library.

Is there a design pattern that would simplify this process? Maybe some sort of reference counting?

Body:
Often you can use a pattern like this:

class C {
public:
  void foo() {
    underlying_foo(handle.get());
  }

  void bar() {
    // transfers ownership
    underlying_bar(handle.release());
  }

  // use default copy/move constructor and assignment operator

private:
  struct deleter {
    void operator()(T* ptr) {
      deleter_fn(ptr);
    }
  };
  std::unique_ptr<T, deleter> handle;
};

By using release you can explicitly transfer ownership. However this is confusing and you should avoid it if at all possible.

Most C libraries have a C++-like object life cycle (object allocation, accessors, destruction) that maps nicely onto the C++ pattern without ownership transfer.

If users need shared ownership, they should use shared_ptr with your classes. Don't try to implement any ownership sharing yourself.

Update: If you want to make the transfer of ownership more explicit, you can use a reference qualifier:

void bar() && { ... }

Then users must call bar on lvalues like this:

C o;
std::move(o).bar();  // transfer of ownership is explicit at call site


答: If the library can free things internally, and the scenarios where this can happen is well documented, then all you can do is set a flag like you're doing already.</p>


答:
Should a database table(s) structure match its intended data structure(s) in the logic?

In short: NO, it is a technical failure to think in that way.

Any project should have its database design and structure based on ONLY and ONLY on business requirements that are provided and approved by the project stake-holders. Any minor alterations and improvements to DB structure might potentially be done in the later stages of the project, depending on trade-offs of performance and usability.


答:
To answer your questions in one word, yes.

Having a class call its own getters and setters adds extensibility and provides a better base for future code.

Say you have something like this:

```<code>public class Vehicle
{
    private int year;
    private String make;

    public Vehicle(int year, String make)
    {
        setYear(year);
        setMake(make);
    }

    public void setYear(int year)
    {
        this.year = year;
    }

    public void setMake(String make)
    {
        this.make = make;
    }
}
</code>```

Calling the setters for year and make currently may not add any functionality, but what if you wanted to add something like input validation to the setters?

```<code>public class Vehicle
{
    private int year;
    private String make;

    public Vehicle(int year, String make)
    {
        setYear(year);
        setMake(make);
    }

    public void setYear(int year)
    {
        if(year > 0)
        {
            this.year = year;
        }
        else
        {
            System.out.println(year + " is not a valid year!");
        }
    }

    public void setMake(String make)
    {
        this.make = make;
    }
}
</code>```

Body:
To answer your questions in one word, yes.

Having a class call its own getters and setters adds extensibility and provides a better base for future code.

Say you have something like this:

public class Vehicle
{
    private int year;
    private String make;

    public Vehicle(int year, String make)
    {
        setYear(year);
        setMake(make);
    }

    public void setYear(int year)
    {
        this.year = year;
    }

    public void setMake(String make)
    {
        this.make = make;
    }
}

Calling the setters for year and make currently may not add any functionality, but what if you wanted to add something like input validation to the setters?

public class Vehicle
{
    private int year;
    private String make;

    public Vehicle(int year, String make)
    {
        setYear(year);
        setMake(make);
    }

    public void setYear(int year)
    {
        if(year > 0)
        {
            this.year = year;
        }
        else
        {
            System.out.println(year + " is not a valid year!");
        }
    }

    public void setMake(String make)
    {
        this.make = make;
    }
}


问:
What aspects make websites load faster?
I want to know what aspects in VPS hosting packages are related to performance for the website which will make it faster in loading for the end useres. And does RAM really matter?</p>

答:
you can also use a tool like https://developers.google.com/speed/pagespeed/insights

which will tell you how to opertimize you site to preform faster

Title: What aspects make websites load faster?


答:
Yes.  Getters and setters represent state, so turn this question around -- do you want to have to keep track of multiple ways of changing an objects state in the same manner unless you have to?

The fewer things you have to keep track of the better -- this is why immutable objects are easier to deal with.

Consider, there is nothing preventing you from having both a public field and a public getter/setter -- but what would you gain?

It may on occassion be desirable or even necessary to directly access the field for one or more reasons, you shouldn't shy away from that if it happens.  But you should really only do it if there is a defined benefit to doing so.


问:
Choosing a proper wording for referring compiler errors
Consider someone is writing a message (or a question at StackOverflow). The context is following:

In my code, I have the following line:

int foo = Bar();

However, the compiler returns an error:

line 42: Bar() is unknown function

I'm puzzled to choose a proper verb instead of "returns". I've seen people using various verbs for it, but I stuck every time I read it:

"returns" can be confused with a function return value;

"throws" is for exceptions;

"prints" has a little sense as the compiler output is not always printed;

"outs", "outputs", or "gives" do not sound professional;

"the compiler complains" sounds a bit like personification of the compiler;

What is the proper verb in this situation?

答:
I would go with

Compile fails with the error "Fizzy buzzy Bizzy fuzzy"

I would stay far away from throw, also print and return aren't particularly great but throw is a downright misnomer.


答:
You are quite right that neither "return" nor "print" fits this situation well. To describe it accurately would require a longer verb phrase such as "compilation fails with an 'unknown function' error" or "results in an 'unknown function' error".

Luckily, the verb is the least important part of a question title - I'd say that it is completely unnecessary. What matters is that you manage to describe the situation and the error type, e.g. "'Unknown function' error with in-line declaration". Combined with the Tag "Java" that tells someone browsing the overview all they need to know.

Title: Choosing a proper wording for referring compiler errors

Body:
Consider someone is writing a message (or a question at StackOverflow). The context is following:

In my code, I have the following line:

int foo = Bar();

However, the compiler returns an error:

line 42: Bar() is unknown function

I'm puzzled to choose a proper verb instead of "returns". I've seen people using various verbs for it, but I stuck every time I read it:

"returns" can be confused with a function return value;

"throws" is for exceptions;

"prints" has a little sense as the compiler output is not always printed;

"outs", "outputs", or "gives" do not sound professional;

"the compiler complains" sounds a bit like personification of the compiler;

What is the proper verb in this situation?


问:
UML modeling tool for Linux
I am starting a new project using Eclipse under Linux and I am looking for a UML 2.x modeling tool not just a diagramming tool.

Do anyone has experience with UML plugin for Eclipse? Does it support all UML diagrams?

Do you recommend another modeling tool?

If you have been in a similar situation, what did you end up doing anyway?

答: I've used Poseidon for UML some years ago, it runs well under Linux. It's a tool with a lot of features, a nice user interface and it can integrate to Eclipse for it's professional version. Despite of it's community version, it's not free at all. </p>

Title: UML modeling tool for Linux


问:
"Do you have any questions for us?" In an interview
You know the prospective company fairly well but are asked "Do you have any questions for us?".  To show interest, what are some of your favorite questions to reply?</p>

答:
I have been giving a great deal of interviews recently, and here are some of the questions I have received from potential candidates.

(not such good ones)

How did I do?

What do you think of my skills?

So do you think you will hire me?

(good ones)

What source control tool do you use?

What development methodology do you
use?

Do you use Agile?

What is your day like?

Do you like it here?

What part of your job do you like the least?

What is the best and worst part of your job.

Any questions that show the interviewer that you are seriously considering working and that you are interested/serious in/about your job are good. Have questions ready at your interview and even if they don't ask you, still say: "Do you mind if I ask you some questions about this position/job"


答:
"Compiler reports an error" sounds appropriate and is actually used in literature.

It does not necessarily "fail" or "return", because it can carry on and report more further errors, warnings or notes.


答:
If the responsibility for cleaning up dynamically allocated stuff shifts between your wrapper class and the C library based on how things get used, you are either dealing with a badly designed C library, or you are trying to do too much in your wrapper class.

In the first case, all you can do is keep track of who is responsible for the cleanup and hope no mistakes are made (either by you or by the maintainers of the C library).

In the second case, you should rethink your wrapper design. Does all the functionality belong together in the same class, or can it be split into multiple classes. Perhaps the C library uses something similar to the Facade design pattern and you should keep a similar structure in your C++ wrapper.

In any case, even if the C library is responsible for cleaning up some stuff, there is nothing wrong with keeping a reference/pointer to that stuff. You just need to remember that you are not responsible for cleaning up what the pointer refers to.


答:
```<code>int gcd(int a, int b)
{
   while(b>0)
   {
      int t = a%b;
      a=b;
      b=t;
   }
   return a;
}
</code>```

Probably not famous, but one of my favorites. To most it's not immediately apparent why it works.

Body:
int gcd(int a, int b)
{
   while(b>0)
   {
      int t = a%b;
      a=b;
      b=t;
   }
   return a;
}

Probably not famous, but one of my favorites. To most it's not immediately apparent why it works.


问:
Securely changing system configuration from a web application
I need to write a web application that acts as a configuration interface for some system services. Meaning it will probably change some kind of configuration file and has to restart (linux) system services.

I was wondering how to design such a thing in a secure way. It is very similar to router web interfaces and such, so I had a quick look at some of these as well as webmin.

Basically, I could run the web service/CGI-Script/etc. with root privileges, filter the input as good as possible and just write to the system and execute whatever program I'd like.

This does not seem very secure. I would like to achieve some kind of privilege separation.

Maybe having my web app run as unprivileged user and pass the Information to some privileged daemon/service, i.e., having a Python web app writing the infos to a file and notifying the daemon or use unix sockets to communicate with this backend program.

Any ideas or experience you could share regarding this issue?

Thank you very much in advance.

答: You've mostly answered your own question.  You're right to dislike running the web app as root, no matter how you run it.  You're right to look at separation of priviledge to bridge the gap between the less- and more-secure environments.  I'd just add that your chosen bridge (and I like text files for this) should describe the action to be performed, not the technique by which it is performed.  So have your less-secure environement write an "action file" that says restart_cron instead of /etc/init.d/crond restart.  And have your more-secure environment check the contents of the "action file" very carefully, especially anything that it winds up invoking as part of a command.  In general, if you think of a way to make the more-secure environment simpler to use by the less-secure, go in the opposite direction.


问:
Soft Real Time Internet Aplication
I am building a tutoring application that multiple students can sign into the same session with a tutor.

My question is, for example, if I sent out a command to draw a line, do I need to wait to see that all connected students propagated the command. Now, it relies that requests will be processed in order.

But consider this. If I draw one point, drag and draw another point, it will draw a line. But if I don't wait to see if each step propagated to all students' screens successfully, a student might receive an instruction of drag, draw, draw.

However, waiting for each connected user's input seems to be a very slow approach. Is there any way I can solve this efficiently? Or is this a problem at all?

答:
One way I could think of is to encode a unique numerical order for each draw instruction, so if they were sent out of order, the program picking it up would know that it was out of order and could correct the drawing accordingly.

I'm not sure this way is the best way, though, as it means that if the packets are wildly out of order, the drawing will fluctuate a lot.

Title: Soft Real Time Internet Aplication


问:
Is "frontend" generic term or it is used only in web design?
When I read about frontends, it always mentiones webpages. Can it be used in different contexts, e.g. desktop applications?</p>

答:
The term is generic and it tends to be used in n-tiered applications and refers to the UI.

It is not limited to n-tiered applications - in a single tiered application, if you have good separation of layers (say UI, business logic and infrastructure), you would still refer to the UI as the front-end.

So, you can use it whenever you are specifically talking about the UI - the interface that the end user uses.


答:
The term is used both in design and development, including development of desktop software. The term targets a part of a system which is intended to be accessed by a customer or a user.

1. In web development:

It is not unusual to make the difference between:

Front end: the website or web application itself, as it is used by people outside the company,

Back end: the part of the web application which is used only by people with specific permissions and which allows them to execute administrative tasks.

Note: moderators would be qualified as people outside the company, so controls used by moderators are part of front end.

2. In SOA/SASS:

When services are involved, front end would be everything directly accessible by the users/customers. A desktop application installed by the user and which connects to a bunch of web services would be qualified as front end.

Services themselves, in this context, would be excluded from the front end.

Note: if a web service is the actual product, it may be qualified as a front end. For example, Twilio web service is the front end.

Title: Is "frontend" generic term or it is used only in web design?

Body: When I read about frontends, it always mentiones webpages. Can it be used in different contexts, e.g. desktop applications?</p>


问:
Determinism of functions using PRNG in Clojure and functional languages
I'm a bit surprised by a sentence found in the book "Clojure Programming" (1st [and only as I write this!?] edition), page 78:

It should be obvious that it's impossible to deterministically test a
  function that depends upon a random number generator

Well, to me it's not obvious at all.

First in the context the book definitely talks about a PRNG (that sentence just follows a mention of java.util.Random, which is a PRNG), not a real random source.

Seen that functional languages that do support higher-order function can be, well, passed functions...  Why not simply pass the random generator function itself to the function you want to be able to deterministically test?

If I've got something like the following function (it's just an example) and the PRNG itself is deterministic, why would it be impossible to deterministically test the following function:

```<code>(defn shuffle-deck [deck  last-generated-number   prngf]
      ...)
</code>```

I realize that instead of keeping a (global?) reference to your random generator, you need to keep a reference to the last generated number (and update it accordingly) but that's basically it.

You can then test/reproduce the behaviour of any function using a PRNG as long as you pass the PRNG and 'the random number you're currently at'.

It's not unlike deterministic game engines (like Blizzard's Warcraft III) where the replays only contains the player inputs, the time at which they happened and the overall seed to the PRNG.

Basically I'm a bit confused: I've always seen PRNG as something that is not "real randomness" and I've got the impression that functional languages accepting higher-order function make it particularly easy to reproduce behavior of functions depending on PRNG.

So, is that sentence of the book (which I found a great book btw) complete rubbish?  I sure do not find it "obvious" at all...

答:
It depends on what the author had in mind when they made the statement. You're certainly correct that by using a deterministic PRNG, you can then test functions which are deterministic other than the PRNG they use.

On the other hand, if what you're testing depends on the PRNG having some behavior common to them (like having at least a certain period or a particular distribution) and your test PRNG does not provide those behaviors, you'll break your tests (or at least neuter them).

In general though, I would consider the sentence to be incorrect. It's commonplace to use deterministic PRNG's to deterministically test functions that use them as input.


问:
How to you "sell" support as an career option
We find it relatively easy to hire developers to work on various projects.

The problem arises when the project is finished but still needs to be supported.

We really battle to get people to join the support team. It's seen as dead-end, career-limiting, boring, second-class etc.

Currently, we get round this by getting the project team to assign some of their team to the support team for a while. Part of the assignment is to do a "brain dump" of the project so that the support team understands it. This works as long as the assignment is only for a fixed period.

Trying to hire people to work in support full-time is a problem. There are few applications and the calibre is not particularly high.

(The financial reality though is that support can be very lucrative for a company and once you get a reputation, you get approached by other companies to do their support even though you weren't involved in the original development.)

答:
A few thoughts:

1) You say it's seen as dead end and career limiting.  If this isn't true and people have gone on to other things (development, project management, running the team) then I'm sure you've got examples you can use.  If you don't have examples then you might have to accept that it is dead end and career limiting and need to address these issues.

2a) If support includes bug fixing then why are they separate?  If someone coded it badly to begin with then what are you teaching them by giving their mess to someone else to sort out.  Moreover if the support developers aren't seen as as good as the developers how on earth can you expect them to fix what the developers couldn't get right?  Seriously the rule should be you wrote it, you fix it.

2b) If support doesn't include bug fixing then they're very different jobs and emphasise different skills.  You shouldn't be worrying about cross over here any more than you worry about cross over between development and cleaning.

3) You say it's lucrative for the company - then make it lucrative for the people involved.  This might be through better money, better training, better kit and giving them everything they need to do this stuff really really well.  If there is money available make it a great job.

The issue from reading your post is that you don't seem to believe it's a good job.  If that's true then no wonder you can't sell it as one.


问:
Should the methods of a class call its own getters and setters?
Where I work I see lots of classes that do things like this:

```<code>public class ClassThatCallsItsOwnGettersAndSetters {

    private String field;

    public String getField() {
        return field;
    }

    public void setField(String field) {
        this.field = field;
    }

    public void methodWithLogic() {
        setField("value");
        //do stuff
        String localField = getField();
        //do stuff with "localField"
    }
}
</code>```

If I wrote this from scratch, I would have written the methodWithLogic() like this instead:

```<code>public class ClassThatUsesItsOwnFields {

    private String field;

    public String getField() {
        return field;
    }

    public void setField(String field) {
        this.field = field;
    }

    public void methodWithLogic() {
        field = "value";
        //do stuff
        //do stuff with "field"
    }
}
</code>```

I feel that when the class calls its own getters and setters, it makes the code harder to read.  To me it almost implies that complex logic is happening in that method call even though in our case it almost never is.  When I'm debugging some unfamiliar code, who's to say that the bug isn't some side effect in that method?  In other words, it makes me take lots of side trips on the journey of understanding the code.

Are there benefits to the first method? Is the first method actually better?

答:
Both methods have their use cases. As public setter keeps field value (and/or bound values) consistent, you should use setter when your method logic does not interfere with this consistency logic. If you just set your "property", use setter. On the other hand, there are situations, where you need direct access to some fields, for example bulk operations with heavy setter, or operations where setter concept is too simple.

It is your responsibility to keep things consistent. Setter does this by definition, but cannot cover complex cases.


答:
Wikipedia has an article that answers this question directly, front and back ends.

In the context of compilers:

Front end validates the syntax and semantics then outputs some intermediate representation, such as an AST.

Back end generates the assembly or translated code.


问:
Wrapping Primitives to Enable Returning null -- Bad Practice?
I am frequently tempted to wrap integers, etc, solely for the purpose of writing methods that can return null. Negative 1 can work in many cases, but too often (especially in sound) it's a valid return value.

Often, to get around this, I am returning a reference to a larger object that contains the primitive in question and calling a getter. This seems less efficient than the wrapper, and in some cases less encapsulating.

So, are there any penalties with wrapping for this reason? Does anybody do this? Does this smell?

答:
One technique that I sometimes use in C/C++ is to have the function return a boolean value indicating whether the function was able to compute its result, and then pass a pointer as a function argument to where the function can store its result. If the function returns true you can grab the value you want using the pointer. For languages which don't have pointers, such as Java, you can pass in some mutable container object (usually an array) to get a similar effect. This isn't really common in Java, although I do remember seeing it used once or twice before. This approach has the benefit that you don't need to wrap primitives, but you do need to create the array in languages like Java.

Scala and Google's Guava library for Java offer implementations of the Option pattern for doing this sort of thing in a different way. Instead of returning null when your function can't return a value, you return an instance of Option which has no value, and then the caller uses methods of the returned Option object to determine whether the actual return value was computed by the function or not and to also get the value if it is valid. Since the Option classes are generic, you still have to wrap your primitives anyway, so this approach actually increases the amount of overhead needed to handle the return value. However, Options do make the code easier to understand than checking an Integer return value for null. Also, it makes it obvious from the function signature that the function may not always return a valid value.

Here's a contrived example of the former approach in Java:

```<code>boolean divide(int[] out, int a, int b) {
    if (b == 0) return false;
    out[0] = a/b;
    return true;
}

int x = ...;
int y = ...;
int[] out = new int[1];
if (divide(out, x, y)) {
    int d = out[0];
    // do something with d
} else {
    // deal with division by zero
}
</code>```

and the latter with the Guava classes:

```<code>Optional<Integer> divide(int a, int b) {
    if (b == 0) return Optional.absent();
    return Optional.of(a/b);
}

int x = ...;
int y = ...;
Optional<Integer> o = divide(x, y);
if (o.isPresent()) {
    int d = o.get();
    // do something with d
} else {
    // deal with division by zero
}
</code>```

You should also ask yourself if you should be throwing an exception instead of doing this. For example, in the above, it would probably just be better to always do the division and handle the ArithmeticException, or check if y is zero before calling the function. The right decision depends on a number of factors, such as whether the overhead of exception handling is going to be a problem for your use case.

Body:
One technique that I sometimes use in C/C++ is to have the function return a boolean value indicating whether the function was able to compute its result, and then pass a pointer as a function argument to where the function can store its result. If the function returns true you can grab the value you want using the pointer. For languages which don't have pointers, such as Java, you can pass in some mutable container object (usually an array) to get a similar effect. This isn't really common in Java, although I do remember seeing it used once or twice before. This approach has the benefit that you don't need to wrap primitives, but you do need to create the array in languages like Java.

Scala and Google's Guava library for Java offer implementations of the Option pattern for doing this sort of thing in a different way. Instead of returning null when your function can't return a value, you return an instance of Option which has no value, and then the caller uses methods of the returned Option object to determine whether the actual return value was computed by the function or not and to also get the value if it is valid. Since the Option classes are generic, you still have to wrap your primitives anyway, so this approach actually increases the amount of overhead needed to handle the return value. However, Options do make the code easier to understand than checking an Integer return value for null. Also, it makes it obvious from the function signature that the function may not always return a valid value.

Here's a contrived example of the former approach in Java:

boolean divide(int[] out, int a, int b) {
    if (b == 0) return false;
    out[0] = a/b;
    return true;
}

int x = ...;
int y = ...;
int[] out = new int[1];
if (divide(out, x, y)) {
    int d = out[0];
    // do something with d
} else {
    // deal with division by zero
}

and the latter with the Guava classes:

Optional<Integer> divide(int a, int b) {
    if (b == 0) return Optional.absent();
    return Optional.of(a/b);
}

int x = ...;
int y = ...;
Optional<Integer> o = divide(x, y);
if (o.isPresent()) {
    int d = o.get();
    // do something with d
} else {
    // deal with division by zero
}

You should also ask yourself if you should be throwing an exception instead of doing this. For example, in the above, it would probably just be better to always do the division and handle the ArithmeticException, or check if y is zero before calling the function. The right decision depends on a number of factors, such as whether the overhead of exception handling is going to be a problem for your use case.


答:
The quote comes from a paragraph that goes like this:

It should be obvious that it’s impossible to deterministically test a function that depends upon a random number generator. For all intents and purposes however, the same is
  true of any function that depends upon or produces external state, since it is often very
  difficult to enumerate (...) all the potential edge
  cases and failure conditions related to that state. This is what mocks are for in testing,
  to dummy up an external data source or sink so that it will reliably behave in ways we
  know ahead of time so as to provoke particular results from a function under test. (...)

The paragraph comes from a section on pure functions that focuses on how pure functions differ from non-pure functions, namely the determinism that comes with the fact that output is a function of the input and input alone - no dependency on an external state. RNG is used as an example of such an external state, but so are things like number of twitter followers or bank account balance.

What author wanted to say is that you can't deterministically test a function like this:

```<code>(defn addRandom [x]
  (+ x (rand-int 10)))
</code>```

since there is an external state involved and calling (addRandom 5) twice could return two different results.

Now, you could refactor this function to break the dependency on the rand call. But then you won't have a function that depends upon a RNG. You would have a higher order function that takes a function that provides a number that might or might not be random, or you would have a function that takes a pair of numbers, and so on. You would have a pure function that you could reason about reliably, since you pushed external state out of the equation. But it would be a different function than the one you started with - one that the sentence you quoted no longer applies to.

Title: Determinism of functions using PRNG in Clojure and functional languages

Body:
I'm a bit surprised by a sentence found in the book "Clojure Programming" (1st [and only as I write this!?] edition), page 78:

It should be obvious that it's impossible to deterministically test a
  function that depends upon a random number generator

Well, to me it's not obvious at all.

First in the context the book definitely talks about a PRNG (that sentence just follows a mention of java.util.Random, which is a PRNG), not a real random source.

Seen that functional languages that do support higher-order function can be, well, passed functions...  Why not simply pass the random generator function itself to the function you want to be able to deterministically test?

If I've got something like the following function (it's just an example) and the PRNG itself is deterministic, why would it be impossible to deterministically test the following function:

```<code>(defn shuffle-deck [deck  last-generated-number   prngf]
      ...)
</code>```

I realize that instead of keeping a (global?) reference to your random generator, you need to keep a reference to the last generated number (and update it accordingly) but that's basically it.

You can then test/reproduce the behaviour of any function using a PRNG as long as you pass the PRNG and 'the random number you're currently at'.

It's not unlike deterministic game engines (like Blizzard's Warcraft III) where the replays only contains the player inputs, the time at which they happened and the overall seed to the PRNG.

Basically I'm a bit confused: I've always seen PRNG as something that is not "real randomness" and I've got the impression that functional languages accepting higher-order function make it particularly easy to reproduce behavior of functions depending on PRNG.

So, is that sentence of the book (which I found a great book btw) complete rubbish?  I sure do not find it "obvious" at all...

Body:
The quote comes from a paragraph that goes like this:

It should be obvious that it’s impossible to deterministically test a function that depends upon a random number generator. For all intents and purposes however, the same is
  true of any function that depends upon or produces external state, since it is often very
  difficult to enumerate (...) all the potential edge
  cases and failure conditions related to that state. This is what mocks are for in testing,
  to dummy up an external data source or sink so that it will reliably behave in ways we
  know ahead of time so as to provoke particular results from a function under test. (...)

The paragraph comes from a section on pure functions that focuses on how pure functions differ from non-pure functions, namely the determinism that comes with the fact that output is a function of the input and input alone - no dependency on an external state. RNG is used as an example of such an external state, but so are things like number of twitter followers or bank account balance.

What author wanted to say is that you can't deterministically test a function like this:

(defn addRandom [x]
  (+ x (rand-int 10)))

since there is an external state involved and calling (addRandom 5) twice could return two different results.

Now, you could refactor this function to break the dependency on the rand call. But then you won't have a function that depends upon a RNG. You would have a higher order function that takes a function that provides a number that might or might not be random, or you would have a function that takes a pair of numbers, and so on. You would have a pure function that you could reason about reliably, since you pushed external state out of the equation. But it would be a different function than the one you started with - one that the sentence you quoted no longer applies to.


问:
Divisional/Sectional comments, good or bad?
I know the general trend against comments explaining how something works, and how it's a good idea to use them only to explain why you're doing what you're doing, but what about using comments as a means of dividing up the code?

Assume you have a script that does a preamble, searches through a bunch of records, prints the records, then closes everything:

```<code>// Preamble
... preamble code, say about 10-15 lines ...

// Find records
... sql query ...
... put records into array ...
... some other stuff ...

// Print records
... printing records, 20-30 lines a record ...

// Close everything
...
</code>```

More of a way to visually divide the code, make it easier to find a certain section. Like if in a month you need to fix the printing code, rather than reading through a couple hundred lines to try and find the right spot, just look at the comments to see where it is.

What actually happens in each section being fairly straightforward and easy to tell what's going on, would this approach to comments be considered good or bad?

Edit:
I'm working mostly with PHP scripts, where you either can't put code into functions, or it's impractical to do so. However, the same sort of thing would apply to large class files, with several methods that do related things, like getters/setters, database updates, etc.

答:
I like this type of commenting.  Not everything factors nicely into a separate class or function.  For example, if you'd have to pass almost the entire stack frame worth of state to such a function/class, you aren't really be decoupling/simplifying anything by factoring the code out.  Even if the code can be factored out, that doesn't mean it should be.  You have to weigh the reusability gains and the gains in readability of the individual steps against the fact that excessive indirection can make the overall flow of the code more opaque.

Even if you do separate out the code into a class/function, comments might sometimes be useful to explain at a high level what the code does.  Comments are not a substitute for readable code, but even readable code doesn't always summarize its high-level purpose, even if it's well-factored into small functions/classes.


问:
Is it possible to read memory from another program by allocating all the empty space on a system?
Theoretically, if I were to build a program that allocated all the unused memory on a system, and continued to request more and more memory as other applications released memory that they no longer need, would it be possible to read recently released memory from another applications? Or is this somehow protected by modern operating system?

I have no practical application for this, I'm just curious. I realize there are some issues with allocating "all available memory" in real-life.

Edit: To clarify, I'm asking specifically about "Released" memory, not accessing memory that is currently allocated by another application.

答:
There are several layers involved here that affect the answer.

If you assume a modern virtual memory operating system, you will not be able to see the remnants of another processes data in pages you allocate.

When a process first gets loaded, the page table is loaded, and potentially frames of real memory are allocated to those pages. At a minimum, the page table or its supplemental table, will contain a map of all memory the process can allocate. This is also where the initial process break, mentioned above, gets set.

While malloc() may, if the process is allowed, cause the process break to change, adding more pages to a processes page (supplemental page) table to satisfy the request, the place where one process may "get another" processes data is at the lower real memory layer.

In both of these scenarios a modern operating system that uses demand paging, or lazy allocation, is not allocating physical memory (frames) yet. The operating system is just "making notes" about which virtual memory for that process is considered valid. Actual memory gets assigned only when needed.

Physical memory or frames get allocated to a process when the virtual page is realized and mapped into a processes page table This is where the potential for data exposure exists. This happens during a page fault. The exposure is because a previous process may have been using that same frame and its data were either abandoned or swapped out, to make room for the current physical memory request. The operating system must be careful to ensure that the requesting processes data is properly swapped in or the frame is cleared (zeroed) before resuming the process. This is also mentioned above as an "old but solved" problem.

This makes it somewhat irrelevant if the other processes memory was "released" or not. Another processes "released" memory still resides in pages assigned to that process and are not usually unmapped until the process ends as they will just get swapped out when memory gets low or they are otherwise evicted. malloc() and free() manage the virtual memory assigned to the process at the (user) level.

In your question, your process, continues to request more and more memory, in theory, pushing all other processes out of memory. In reality, there are frame allocation strategies -- global and local -- that may affect the answer as well. It is as likely that the process will force its own pages out of memory before it is allowed to overrun the operating system and all other processes. Though this goes beyond your initial question.

All this is moot in a system like MS-DOS. MS-DOS (and other, simpler systems) don't use virtual memory (by themselves) and you could easily poke and prod at another "processes" data.

Some good references, that may be easier to understand than the Linux source code would be a good operating systems text book, Operating Systems Concepts by Silberscatz, Gavin, and Gange, or Operating Systems Design by Andrew Tanenbaum. Also something like Nachos from Berkeley or Pintos from Stanford are small operating systems built for learning and have these same ideas within them.


问:
Are these SQL concepts for beginners, intermediate, or advanced developers?
I've been learning SQL recently and practicing with MySQL/Postgres and soon Oracle DB. I've also search the web for a 'road map' study of databases but couldn't find one, unfortunately.

I want to understand where and why particular database concepts fall on the scale from beginner to intermediate and advanced. I'm thinking about relational databases for the most part.

Please explain how to lay out skills listed below in a progression of Beginner -> Intermediate -> Advanced for what level of developer should know them:

Where clauses

Update syntax

Joins

Alter and Create statements

Temp tables

Cursors

Indexes

Foreign keys

Constraints

Transactions

Subqueries

Pivots

Aggregate functions

Profiling

OLAP and OLTP

Triggers

Execution plans

Execution hints

Performance counters

Normalization

答:
I would say there are two types of things to know in regards to SQL (this is true of many technologies really), there are specific technical things like joins, subqueries, unions, etc which you understand or don't, and then there's things like database design and data modelling which has a gradient of skill in it, like art. You get better over time with those softer things, but never "know" them because there's no "they work this way" with them.

That said, here's a general layout I would go with, and am absolutely open to comments/thoughts from others where I may be wrong.

Beginner

Where clauses (in, between, etc)

Update syntax

Inner vs left vs right join understanding and usage

Syntax for altering and creating structures

Temp tables and their usage

Cursors

Basic idea what indexes are for, though not how they work

Understanding of what foreign keys are for and how to work around them (cascading deletes etc)

Understands basics of transactions

Understands constraints

Intermediate

How indexes work, difference between clustered, non-clustered, etc, what a page is and how they layout

Understanding of subqueries, and can think through using them in joins and wheres

Pivots

Can think through joining a table on itself when relevant

Can generate complex data reports via group bys with aggregate functions

Can do basic profiling just in a monitoring/debugging capacity like reading a log

Understands the difference between OLAP and OLTP and when/where to use OLAP structures

Knows how to use triggers and not to use them

Understands transactions and can layer them handling failures up the stack

Advanced

Can read an execution plan, and understand how the different parts of the query effect it

Can tune queries with execution hints without screwing up performance (parallelism hints, index hints, loop hints, et al)

Can profile and use traces for identifying and understanding statistics of executions under real-world load

Knows what the data structures are on the disk

Can use performance counters and understand what the database load and behaviour is from monitoring them

Knows how to design an OLAP cube and do advanced data mining with one

Knows how to use triggers and how to use them safely, with minimal risk

Knows how to use distributed transactions even with layers

That's all I could come up with off the top of my head. Please leave comments mentioning others I missed or if I put something in the wrong place. I'm not advanced enough to know a huge list of advanced techniques to put down heh


答:
Here is the scale I use while interviewing candidates. This is obviously my own personal opinion, scales can easily vary:

First, I am looking for database skills, not specifically "SQL".

Beginner:

Knows basic SQL syntax

Can select and filter data across multiple
tables

Understands inner/outer/cross joins

Vague understanding of
normalization, indexing, transactions, locking

Intermediate:

Understands differences between procedural and declaritive styles for SQL

Experience with at least one DBs SQL extensions (PSQL, TSQL, etc)

Understands, and can design a database in, third normal form

Understands and can implement indexing

Understands transactions, and can use them in a single database

Knows when and how to analyze an execution plan

Advanced:

Understands when and how to denormalize a database

Understands how to setup distributed transactions across a database and integrated systems

Can setp a database for high availability, data recovery, etc

Deep unuderstanding of each DB engine's internal workings (at least two)

Extra points for significant exposure to data warehousing and reporting

Extra points for significant exposure to variants of NoSQL, and a rational set of criteria for when to use what

Title: Are these SQL concepts for beginners, intermediate, or advanced developers?

Body:
I've been learning SQL recently and practicing with MySQL/Postgres and soon Oracle DB. I've also search the web for a 'road map' study of databases but couldn't find one, unfortunately.

I want to understand where and why particular database concepts fall on the scale from beginner to intermediate and advanced. I'm thinking about relational databases for the most part.

Please explain how to lay out skills listed below in a progression of Beginner -> Intermediate -> Advanced for what level of developer should know them:

Where clauses

Update syntax

Joins

Alter and Create statements

Temp tables

Cursors

Indexes

Foreign keys

Constraints

Transactions

Subqueries

Pivots

Aggregate functions

Profiling

OLAP and OLTP

Triggers

Execution plans

Execution hints

Performance counters

Normalization


问:
Handling unexpected features during sprint
Our team is going to adopt scrum and agile technics. We've got a product, which we develop for multiple customers. This customers supplied us with necessary requirements, so everithing is fine to adopt agile techinics.

But at some moment (for example during sprint), new customer apears, and he wants to get a demo of product slightly different from what we have now. This may be some new features or minor differences in behavior. And he wants to get this demo for example during the week. It is very important to show that our product supports this features (because otherwise he will address to our competitors), so we have to develop this features (may be partly) during the week.

How we must handle this sort of features with agile? Move them to current sprint backlog? Or split one team to two and create another sprint? Or may be there is another way?

答:
No customer worth having wants less than a week worth of programming.

Show them what you can do, and say you can modify it to do what they want once they sign the deal. Then schedule it for some future sprint and get it done.