问:
Support Multiple versions of Mobile apps
We are building a suite of native mobile applications to supplement our existing application that currently only supports a web interface to the server. The application can be installed and hosted by clients on their own infrastructure or hosted by ourselves for clients who want to make use of it. Big enterprise customers typically chose to self-host whilst smaller customers choose our hosting option.

We need to support multiple versions of the application. Not all customers want to upgrade at the same time. With the web interface, supporting multiple versions are not difficult as the web interface automatically uses the server version associated with its server installation. With mobile applications where you typically only have a single app available in the App Stores, the support for different levels of the Server API and functionality in the mobile app becomes a challenge. I'm interested to know how other people are solving the issue. To my mind you have options like:

Support multiple versions of the app in the app store.

Build support into the mobile applications to automatically determine the API version of the server it is talking to and route calls to the relevant server API endpoints. Also introduce use some kind of feature toggle mechanism to enable/disable functionality in the mobile application based on what's available in the different server versions.

Do not use the app store for deploying your app. Points users to a version specific URL they can use to download and install the app.

Option 1 - IMO will create confusion for the users of the app. There also isn't a nice migration path from one version of the app to the next as it really is two separate applications.

Option 2 - on the other hand can quickly become very complex if you take into account that your UI visuals now basically need to adapt to whatever functionality is available in the version of the server API it is talking to. It also needs to support the different versions of the server API calls it need to make.

Option 3 - is possible in the Android world when doing side-loading of your app, but as far as I know not supported in iOS and I'm not sure what the picture will be for Windows 10 mobile apps going forward.

What other approaches are there to tackling the issue? Please don't debate the fact that we are writing native apps. That's not what I'm asking. I'm looking for guidance on how other people are tackling the issue of supporting multiple versions of the same native mobile app talking to different versions of a server API.

答:
I've dealt with this in a slightly different context, but what we came up with was that if you used our public server we required you to upgrade.  If you self hosted, we allowed you to stay on whatever version you liked.

I know that isn't the most customer friendly answer, and it might not be an option depending on your situation, but it was the stance we ended up taking.

One thing to note: we ended up having to do a lot of one-offs based on old baselines that were being self-hosted when we found security issues or significant bugs.  If you support multiple versions, whether the way we did or if you end up supporting multiple APIs fully, you need to make sure that you have rock solid configuration management and source control.  As you find bugs, make sure to take the time to source them back to were they originated because you might have to fix it on a old branch.


问:
Android: Pattern for checking requirements at startup?
My app's launcher activity checks a bunch of requirements like whether GPS is enabled, there's a network connection, the app has device administrator privileges, etc.  Some of these checks display dialogs or take the user to another activity to resolve the unsatisfied requirements.  I'm looking for a way of doing this that's easy to extend with more requirements and easy for others to read and understand.

My original solution was to perform the checks sequentially, each in its own method, with each method either taking remedial action or calling the next method in the sequence.  The sequence is started in onResume(), so upon returning from another activity it picks up with the first check that doesn't pass.  This got messy fast because some of the requirements are conditional.  For example, on Lollipop it checks if the app is the device owner, and whether it might be able to become the device owner.  If it can, it tells the user to run the appropriate adb shell command.  Naturally, this whole sequence of checks is skipped on KitKat.  So the chain of methods is actually more like a tangled braid.  It's hard to trace the logic of it or verify that each step eventually calls the next under all possible conditions.  I'm reluctant to make any changes to it, and I just wrote it myself a couple weeks ago.

My other idea was to number the steps (or associate them with the elements of an enum) and pass the last-completed step between activity instances.  But I anticipate this getting messy, too.

How would you structure this?

答: We used put together a single method that did nothing but determine what things had to be set up and returned a value that was passed into a second method which was really just a giant switch statement.  Each element (such as isGpsAvailable) had its own method that was placed in the appropriate case depending on the environment.</p>

ContentLicense: CC BY-SA 3.0


问:
JWT based webservice authentication
I'm currently writing a web service that will be consumed by an android app.

To access user specific content, one must authenticate against the service.

Since I'm not (primarily) using a webbrowser to make calls to my API, a solely session based authentication is not an option.

I don't want to pass the users credentials on every call either, so I decided to use a JWT[1] based authentication.

Edit: A few more details

The webservice is running on node.js.

The following modules play a key part in context to the question : express is used for the endpoints, passport for authentication, jwt-simple  to generate tokens. Not directly relevant for the question but involved in the process is bcrypt-nodejs for encryption and sequelize to query the database, for which postgresql is used.

So far, the process looks the following - using example endpoints

A first call is made to /api/auth/login/, passing along the username and the password of the authenticating user.

The api returns the users information stored in the database, along with a token. e.g.
{success: true, user: {id: 42, token: aaa.bbb.ccc}}

Any subsequent request passes said token as a query parameter to authenticate the same user.

The question that rises now is: How do I correlate the token to a user and verify its validity.

The options I see are the following.

Since the token carries a payload, it's actually enough to put the users id into it and assume that if the token properly decodes it's valid and the API call will be made with privileges of the user whose id is contained in the payload.

Since the token is encoded using a secret only known to the server, it shouldn't be possible to fake a token, unless someone gets its hands on the secret.

other claims as exp or iat can be included as well.

Upon generation of the token, it will be added to a tokens table which contains the token and its corresponding user id (id | user_id | token).
When a request is made, the database will be queried for existence of the token and only if an entry exists, its user_id will be used.

Long story short, my question breaks down into these:

Is it necessary/sound to add the token to a database or can I just use the payload to identify the user?

Does it make any sense to change the servers secret - used to encode the token - about every week, hence invalidating any token generated previously?

Using this approach an additional query against the database has to be made on every single request.

[1] - http://jwt.io/

答:
Is it necessary/sound to add the token to a database or can I just use the payload to identify the user?

I think both approaches are fine. I've implemented token based authentication in .Net, and we put all identity related information in the token. I would argue it's more scalable, especially for a web farm. All the authentication information we need is in the token itself, so we don't need to ask database for additional information. But, the size of token could potentially be very large. Another problem is it's not easy to implement logout. The token is valid until it expires, it's not easy to revoke it. See here.

You can also put required information in the  database. And the token itself only contains something like a "session id". It's now more like a traditional cookies-based authentication. However, you have to deal with some other problems like where to store session information (cache or database), use a shared session database or each machine keeps its own session data, etc.

Title: JWT based webservice authentication


答:
Look at what will happen...

Option 1 will generate support calls when users install the wrong version.  There will always be one user who either can't read or pick the latest version thinking they know better... and you'll have a large number of versions to potentially backport fixes to should you need to.

Option 2 adds some complexity to the UI code, how much depends on how well the UI is written to be adaptive.  But it has the best user experience.

Option 3 can't happen on iOS (Android and Windows will allow it in certain configurations) which means different behaviours for different platforms.  That makes things inconsistent which is a recipe for trouble.

So out of those, making a responsive UI and targeting the right endpoint is by far the best way to go for your users.

Title: Support Multiple versions of Mobile apps

Body:
We are building a suite of native mobile applications to supplement our existing application that currently only supports a web interface to the server. The application can be installed and hosted by clients on their own infrastructure or hosted by ourselves for clients who want to make use of it. Big enterprise customers typically chose to self-host whilst smaller customers choose our hosting option.

We need to support multiple versions of the application. Not all customers want to upgrade at the same time. With the web interface, supporting multiple versions are not difficult as the web interface automatically uses the server version associated with its server installation. With mobile applications where you typically only have a single app available in the App Stores, the support for different levels of the Server API and functionality in the mobile app becomes a challenge. I'm interested to know how other people are solving the issue. To my mind you have options like:

Support multiple versions of the app in the app store.

Build support into the mobile applications to automatically determine the API version of the server it is talking to and route calls to the relevant server API endpoints. Also introduce use some kind of feature toggle mechanism to enable/disable functionality in the mobile application based on what's available in the different server versions.

Do not use the app store for deploying your app. Points users to a version specific URL they can use to download and install the app.

Option 1 - IMO will create confusion for the users of the app. There also isn't a nice migration path from one version of the app to the next as it really is two separate applications.

Option 2 - on the other hand can quickly become very complex if you take into account that your UI visuals now basically need to adapt to whatever functionality is available in the version of the server API it is talking to. It also needs to support the different versions of the server API calls it need to make.

Option 3 - is possible in the Android world when doing side-loading of your app, but as far as I know not supported in iOS and I'm not sure what the picture will be for Windows 10 mobile apps going forward.

What other approaches are there to tackling the issue? Please don't debate the fact that we are writing native apps. That's not what I'm asking. I'm looking for guidance on how other people are tackling the issue of supporting multiple versions of the same native mobile app talking to different versions of a server API.


问:
C#6: Should I refactor my code using Resharper for the new features?
C# 6 is here for a while now and brings with it some syntactic sugar that Resharper is kind enough to highlight and recommend that I "migrate to". Should I apply these fixes automatically to the entire code base and commit? Even though this question can apply to any new feature in the language, the main ones I'm considering applying are:

Use string interpolation instead of string.ToString

Change property from get {...} to expression body ( => )

Use null propagation

Make auto-property get-only

What if this is hundreds of changes? What if it's thousands?

答:
If you were talking about manual refactoring to bring your code up to "C# 6.0 standard", I would heavily vote against refactoring parts of your code in areas you are not currently working with. That would bring only a minimal benefit for a certain risk of breaking things unintentionally.

However, you are talking about an automated migration. In such a situation, you can consider letting your refactoring tool apply the steps if you first check the following preconditions:

the manual effort is really small

everyone on your team knows the new language features, at least to the degree that he/she can read and understand them

you trust your refactoring tool that it does not break anything when applying those patches (and even then, you should have enough automated tests in place to check this on your own)

the result of the automatic refactoring is really better readable, and you do not have to edit the result manually to reestablish readability.

the new features you want to use from C#6.0 do not enforce an unwanted update to a newer .NET framework version you might not be ready to use yet


答:
It depends.

Not all c# 6 features/uses are available in lower .NET versions (see https://stackoverflow.com/questions/28921701/does-c-sharp-6-0-work-for-net-4-0). If your consumers can't move to the latest and greatest libraries, don't update.

Does your team know the new features? If not, you should maybe do some sort of training before dumping everything in source control.

After that it depends on if your team thinks the syntactic sugar adds to readability. I would probably change a few classes and let your team compare - erring towards the new syntax since people will find new things less readable by default.

Title: C#6: Should I refactor my code using Resharper for the new features?

Body:
C# 6 is here for a while now and brings with it some syntactic sugar that Resharper is kind enough to highlight and recommend that I "migrate to". Should I apply these fixes automatically to the entire code base and commit? Even though this question can apply to any new feature in the language, the main ones I'm considering applying are:

Use string interpolation instead of string.ToString

Change property from get {...} to expression body ( => )

Use null propagation

Make auto-property get-only

What if this is hundreds of changes? What if it's thousands?


问:
How to stop someone from calling URL on server
I am very new to web development and am trying to create a website using client/server model. From what I understand, the front-end (client-side) calls URLs specified on the server to get information. So if my website was www.example.com, when the user clicks a button on my site, a request will be sent to www.example.com/api/buttonClicked, and my server will then run the logic and return a response correct?

But simply by using developer tools on Chrome, anyone can see the URL the request is being sent to (www.example.com/api/buttonClicked) and the data being sent. How can i prevent someone from calling this URL? Or even if they did call it, how can i prevent my server from giving them a response?

If it helps, I am using Flask to build the server

答:
You cannot prevent someone from calling your URL directly.

What you can do, however, is reject invalid requests.

You can add a unique key to each response which is then returned in the next request. If a request has an invalid or missing key, ignore it.

This is the basic idea behind a session. In fact, you may be able to use sessions in your framework to do this (I am not familiar with Flask).


答:
No. You shouldn't. At least, I sure wouldn't hit that "Fix all the things" button.

I love Resharper, but it doesn't always make the best decisions. If it did, it wouldn't have given us the ability to ignore warnings/suggestions with a comment. The fact is, sometimes those refactorings lead to less readable code and, in a few instances, can break things. (I've had some issues with COM Interop code and ReSharper suggestions in the past.)

So, if you are going to hit that big red button, you had better have a darn good suite of tests in place.

That's not saying that you shouldn't do this at all, but I personally would take the time to check and apply the refactorings myself. Perhaps as you're working on a file, or maybe take a few hours to clean up the whole project. Either way, a person needs to review these changes. Don't just let the machine make decisions for you. If I've learned anything as a programmer, it's that the machine isn't always right and all code has bugs. Even code from the wonderful folks at JetBrains.

Related: Does Visual Studio Rot the Mind?


问:
Is there a design pattern for managing deep many-to-many relationships?
I'm having trouble defining this data pattern I've come across working on several applications.

It consists of:

An object type which is composed of many objects itself

A second object type, where each instance 'has many' of the first object

And, each of the sub-objects of the first object are modifiable per each association to the second object type.

A simple example might be:

A programming course consisting of a set of lessons

The lessons are composed of a set assignments.

A course can be assigned to a student.

However, once a course is assigned to a student each lesson and/or assignment can be customized to that student, with removals and additions, to the point where the original course may be unrecognizable.

In my solutions, what this results in is:

On assignment of a course to a student, the course is loaded into memory. Then for each sub-object, a student/sub-object relationship object is generated with the appropriate metadata. Essentially, I'm using the original object as a template to generate the required customizable objects.

This results in a huge amount of data as the sub-objects become more complex and numbered. I'm wondering if there is some optimization or pattern to reduce the amount of logic/complexity required to manipulate this data pattern.

答:
I see a few options depending on what you need: (1) if there are many unique instances that follow a common algorithm, (2) if there are many similar objects or you will generated objects at run-time, and (3) if you want to dynamically modify the object's behavior while running. Note: you can combine all of the patterns I mention here, if need be.

If each "second object type" is unique but follows a similar pattern of behavior, you could use Template Pattern. It sounds like you may be doing this. But to make it explicit, your abstract, base class has general algorithm programmed; certain steps of this algorithm are implemented in the derived classes.

If you will create many objects or if creating objects at run-time is important to you, you could use Factory Pattern.

And if you wish to dynamically change behavior, Stategy Pattern could work. For example, if a student in a regular curriculum is decided to be special needs or to go into an accelerated program. This works by composing the "student" of an object that would represent a base-class of the curriculum. The curriculum would be assigned to a derived curriculum at the student's construction (that sounds weird) and could be reassigned to another derived curriculum later.

(Just FYI, if using (3) Strategy Pattern with C++, you will have to Rvalues for composition.)

To store your objects and second objects, it may be worth considering Iterator Pattern (to cycle through them, add, delete, sort, etc.).

A good reference is Head First Design Patterns, which covers the patterns I mention and their implementation. They work in Java.


问:
When should I use static functions and when should I use non-static ones?
Sometimes, when I'm programming, I have to decide between adding a static method to a class that accepts an instance (or more) of that class or adding a non-static method. Here's an example:

Static

```<code>public class Integer {
    // ...
    public static Integer add(Integer a, Integer b) {
        // ...
    }
    // ...
}
</code>```

Non-static

```<code>public class Integer {
    // ...
    public Integer add(Integer addTo) {
        // ...
    }
    // ...
}
</code>```

In this case the most logical choice would be the first (We think of it as "Take two integers and add them" rather than "Add another integer to an integer, and give us the result"), but sometimes it's not as obvious (for unary operations, for example).

Should non-static functions be reserved only for function which actually modify the state of the object?

Does it depend on the language? For example, in Java, it wouldn't make a difference once compiled, because all objects are actually pointers, but in C-based languages, the first case would pass copies of the object, while the second would pass a pointer and a copy (which suggests that we want to modify it). Also, most programming languages do not allow virtual static methods, so that would probably also make a difference (if you want the method to be overridable, for example).

答:
I program OO mostly in C#, which shares a lot of syntax with Java, so I'll speak from that perspective.

For anything that is a "public API" I use a non-static method.  Rarely do I use static methods.  Why?

If it's virtual/not-final I can override the behavior in a subclass.  In the industry I work in we do a lot of customizations for our customers so this is pretty much the easiest way to override the functionality of our vanilla software suite - make things virtual/not-final and change the stock behavior in a custom overlay.

By being a method on a dependent class/service (even if it's singleton) I can mock the non-static method I'm calling, allowing for unit testing and separation of concerns.

By being a method on a class I can use the decorator pattern to intercept the calls.

There are probably more benefits as well.

I only use static methods if the IDE generates it as such when I'm refactoring the inside of a class so that I'm not repeating myself.  I also use it when I'm consuming an API that requires me to do so (i.e. writing a Main method or the like).

Another good case for it may be general-purpose numerical mathematical methods and utilities, like in your add example.


问:
How can I model this scenario in a graph database?
I'm developing an application where users can tag resources and it's also important to know who tagged the resource with a specific tag.

A graph database seems like a good fit for this and the rest of the application but having only previously used traditonal RDBMSs I'm struggling to see how to model this scenario.

I a relational database I would have a "PersonResourceTag" join table to identify which user applied a particular tag, but with a graph database I can't work out how to associate the person with a tag for a specific resource. Would I need some kind of "PersonTaggedResource" vertex or is there a better way? ...or is this simply not a good fit for a graph database?

答:
Graph Databases are in general, a superset of what an RDBMS can do. The implementations are completely different and you have to forget all the RDBMS idioms when you approach using a Graph Database. The relationships are not modeled with a join table, they are modeled directly into the node with a *relationship". This is called index free adjacency, which is the exact opposite of a join table in an RDBMS.

```<code>Person -> Tags[Tag] -> Resource
</code>```

Where Tag is a Property and the above syntax is very close to the actual GraphQL syntax to query the graph with.

You can get a free copy of Graph Databases from O'reilly, it is a great read.

Body:
Graph Databases are in general, a superset of what an RDBMS can do. The implementations are completely different and you have to forget all the RDBMS idioms when you approach using a Graph Database. The relationships are not modeled with a join table, they are modeled directly into the node with a *relationship". This is called index free adjacency, which is the exact opposite of a join table in an RDBMS.

Person -> Tags[Tag] -> Resource

Where Tag is a Property and the above syntax is very close to the actual GraphQL syntax to query the graph with.

You can get a free copy of Graph Databases from O'reilly, it is a great read.


问:
Features to generate time expiring
There are something out of box to generate time expiring in php?
For example I need to control the access to the system, I was thinking something to verify every first day of every month, and do this in my code.

But it is not 100% safety, since another programmer can remove this line code that verify. Then I thought is it possible, to verify in another server, if the monthly time expire or not? and return the message to the user if the copy expired or not?

What is the best to way to create a licensing features for time expiry?
or I really need to get inside IonCube (Compiled Code Encoding) for example?

What is the best practice?

答:
What first comes to mind is a web validation, each time the users logs in. So , when you make the package, your first write a line with a request to a page of yours with a license-number and that way check consistency. Also, from your site, you should check that if a license has not registered any activity in, lets say a month, then ask for explanations to the people who bought it.

Hope this helps, it aint bullet proof but cuold work!

EDIT:

After the commend and reading some internet articles i found some nice php obfuscators OpenSource. Read this article and see for yourself. This will avoid removing the line of code.

ContentLicense: CC BY-SA 2.5

Title: Features to generate time expiring


问:
Is there any practical trick to remember the difference between big-endian and little-endian?
I don't work every day with big-endian and little-endian problems and thus I find very difficult to remember which one is what.

Recently I got an interview asking the difference between the two; since I didn't remember I decided to "guess" (50% chance, after all) but I failed.

So, is there any wide known pratical trick to remember what is the difference between big endian and little endian?

答:
Big-endian numbers start at the "big end".
Little-endian numbers start at the "little end".

Both are an allusion to the issue of where to start eating your egg, as per Gulliver's Travels.

In this case, "end" is not the opposite of start, it just means any extreme of a (rope|string|number|sequence), thus them not being called "big finishian" or "little finishian" (which would definitely be the opposite of "start").


问:
Is creating a new List to modify a collection in a for each loop a design flaw?
I recently ran in to this common invalid operation Collection was modified in C#, and while I understand it fully, it seems to be such a common problem (google, about 300k results!). But it also seems to be a logical and straightforward thing to modify a list while you go through it.

```<code>List<Book> myBooks = new List<Book>();

public void RemoveAllBooks(){
    foreach(Book book in myBooks){
         RemoveBook(book);
    }
}

RemoveBook(Book book){
    if(myBooks.Contains(book)){
         myBooks.Remove(book);
         if(OnBookEvent != null)
            OnBookEvent(this, new EventArgs("Removed"));
    }
}
</code>```

Some people will create another list to iterate through, but this is just dodging the issue. What's the real solution, or what is the actual design issue here? We all seem to want to do this, but is it indicative of a design flaw?

答:
Is creating a new List to modify a collection in a for each loop a design flaw?

The short answer: no

Simply spoken, you produce undefined behaviour, when you iterate through a collection and modify it at the same time. Think of deleting the next element in a sequence. What would happen, if MoveNext() is called?

An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and its behavior is undefined.
  The enumerator does not have exclusive access to the collection; therefore, enumerating through a collection is intrinsically not a thread-safe procedure.

Source: MSDN

By the way, you could shorten your RemoveAllBooks to simply return new List<Book>()

And to remove a book, I recommend returning a filtred collection:

return books.Where(x => x.Author != "Bob").ToList();

A possible shelf-implementation would look like:

```<code>public class Shelf
{
    List<Book> books=new List<Book> {
        new Book ("Paul"),
        new Book ("Peter")
    };

    public IEnumerable<Book> getAllBooks(){
        foreach(Book b in books){
            yield return b;
        }
    }

    public void RemovePetersBooks(){
        books= books.Where(x=>x.Author!="Peter").ToList();
    }

    public void EmptyShelf(){
        books = new List<Book> ();
    }

    public Shelf ()
    {
    }
}

public static void Main (string[] args)
{
    Shelf s = new Shelf ();
    foreach (Book b in s.getAllBooks()) {
        Console.WriteLine (b.Author);
    }
    s.RemovePetersBooks ();

    foreach (Book b in s.getAllBooks()) {
        Console.WriteLine (b.Author);
    }
    s.EmptyShelf ();
    foreach (Book b in s.getAllBooks()) {
        Console.WriteLine (b.Author);
    }
}
</code>```

Body:
Is creating a new List to modify a collection in a for each loop a design flaw?

The short answer: no

Simply spoken, you produce undefined behaviour, when you iterate through a collection and modify it at the same time. Think of deleting the next element in a sequence. What would happen, if MoveNext() is called?

An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and its behavior is undefined.
  The enumerator does not have exclusive access to the collection; therefore, enumerating through a collection is intrinsically not a thread-safe procedure.

Source: MSDN

By the way, you could shorten your RemoveAllBooks to simply return new List<Book>()

And to remove a book, I recommend returning a filtred collection:

return books.Where(x => x.Author != "Bob").ToList();

A possible shelf-implementation would look like:

public class Shelf
{
    List<Book> books=new List<Book> {
        new Book ("Paul"),
        new Book ("Peter")
    };

    public IEnumerable<Book> getAllBooks(){
        foreach(Book b in books){
            yield return b;
        }
    }

    public void RemovePetersBooks(){
        books= books.Where(x=>x.Author!="Peter").ToList();
    }

    public void EmptyShelf(){
        books = new List<Book> ();
    }

    public Shelf ()
    {
    }
}

public static void Main (string[] args)
{
    Shelf s = new Shelf ();
    foreach (Book b in s.getAllBooks()) {
        Console.WriteLine (b.Author);
    }
    s.RemovePetersBooks ();

    foreach (Book b in s.getAllBooks()) {
        Console.WriteLine (b.Author);
    }
    s.EmptyShelf ();
    foreach (Book b in s.getAllBooks()) {
        Console.WriteLine (b.Author);
    }
}


答:
Creating a new list to modify it is a good solution to the problem that existing iterators of the list cannot reliably continue after the change unless they know how the list has changed.

Another solution is to make the modification using the iterator rather than through the list interface itself. This only works if there can only be one iterator - it doesn't solve the problem for multiple threads iterating over the list concurrently, which (as long as accessing stale data is acceptable) creating a new list does.

An alternative solution that the framework implementers could have taken is to have the list track all its iterators and notify them when changes occur. However, thw overheads of this approach are high - for it to work in general with multiple threads, all iterator operations would need to lock the list (to ensure it doesn't change while the operation is in progress), which would make all list operations slow. There would also be nontrivial memory overhead, plus it requires the runtime to support soft references, and IIRC the first version of the CLR didn't.

From a different perspective, copying the list to modify it allows you to use LINQ  to specify the modification, which generally results in clearer code than directly iterating over the list, IMO.

Title: Is creating a new List to modify a collection in a for each loop a design flaw?

Body:
I recently ran in to this common invalid operation Collection was modified in C#, and while I understand it fully, it seems to be such a common problem (google, about 300k results!). But it also seems to be a logical and straightforward thing to modify a list while you go through it.

```<code>List<Book> myBooks = new List<Book>();

public void RemoveAllBooks(){
    foreach(Book book in myBooks){
         RemoveBook(book);
    }
}

RemoveBook(Book book){
    if(myBooks.Contains(book)){
         myBooks.Remove(book);
         if(OnBookEvent != null)
            OnBookEvent(this, new EventArgs("Removed"));
    }
}
</code>```

Some people will create another list to iterate through, but this is just dodging the issue. What's the real solution, or what is the actual design issue here? We all seem to want to do this, but is it indicative of a design flaw?


问:
Clean Architecture - How to go from "Database Driven" to "Independent of Database"
I am looking for some clarity and hopefully some advice on writing clean architecture for a large system. My Companies "Web Solution" is +-10 years old, my job is to rewrite it. It is written across a few thousand asp classic pages all with their own sql queries with absolutely zero consistency (I spend the vast amount of my maintenance/debugging time fixing these since products may appear in one search and not another etc.). To put it bluntly its tangled knot of code straight out of my worst nightmares to deal with.

Up until yesterday I had a pretty straight forward plan for the re-development and to solve my inconsistency issues...

Choose a user case.

Write one or two stored procs/sql functions to control the dataflow for the selected case i.e. save user, add user, edit user etc.

Update the relevant asp pages on the current system to use the above procs/functions.

End goal - end up with an entirely database driven application, while achieving much needed stability & integrity during development. Once this is achieved I was planning to write a web API (using the same database procedures) and then implement a web UI,Mobile App and anything else needed on top of this API. While daunting this seemed like a pretty decent solution to me, even with its flaws it’s exponentially better than what we currently have to work with.

Then I came across Uncle Bobs Guide to Clean Architecture.

I understand the concept and it seems awesome, all most too good to be true from my current position but the deeper I delved into it the trickier it became in terms of "This is great! Now how would I implement it?” One of the rules the guide calls for is that the application be completely database independent. Meaning what I had planned would never make the cut. I had to admit the cold hard fact that this is a completely foreign concept to me, right from the first day I started learning to program the heart and soul of the application was the DB so it’s very hard for me to adjust my thought process and not treat it as such.

I have done some further reading and was hoping for some feedback to whether or not I’m on the right track, or if there is a cleaner cut, cleaner approach.

PHP is my primary go to language for most web applications so this is the language my theory would most likely be implemented in...

Break the system down to its core use cases and entities. Write Independent objects for each of these.

Write a data interface model, which abstracts from the database (since the database currently is primary source for use cases and entity logic the above objects would likely based of their current table). This would allow me to keep anything DB related in one location and provide the same result of integrity and consistency that implementing stored procs/sql functions would, although this would still not make the application "database independent" since I would have to modify the abstraction layer if I changed providers i.e. from SQL Server to Oracle. This is where my uncertainty comes in, is this a good approach? It’s highly unlikely I would change data sources but who knows? Also If I am going to follow the guide’s architecture I want to do it as closely as possible and I know that if this step is not implemented correctly it would defeat the purpose since the database layer would slowly start seeping back into the primary application model.

Implement a web API using the core objects written in step 1.

Implement API driven UI's for whatever platforms necessary.

I apologise for the essay but I wanted to be as clear as possible in the hopes that this will help get me the best guidance. I would really love to learn and one day be highly proficient in this type of architecture and while there is a ton of online information about its structure and concept there is extremely little on how to implement it, or more on how to change your mind set when developing an application when you are used to the database being the absolute core of the application.

Any kind of feedback will be highly valued and appreciated.
Thanks

答:
First of all, I wouldn't approach a clean architecture in PHP. One of the main goals of clean architecture is to allow the user interface to be considered as essentially a plugin to the application, allowing you to change between types of UI easily. By going with PHP you are restricting yourself essentially to web-based interfaces. If you are familiar with a more architecture-independent language, I would pick that instead.

After that, I would start by developing a simple implementation of one or two use cases with a text user interface and no database - just use a collection to store your business objects. Once you're happy with how that works, you can experiment with how to attach your user interface and database layers in such a way that your original version still works - once you have that working, the rest should be fairly simple.

A few useful things to look up:

MVC frameworks for the language you end up using. MVC (or MVP) works nicely as the UI layer for clean applications

The Repository pattern for data access - this is probably the best way of separating your data access layer from your application layer

Hexagonal Architecture - this is an alternative name for the same concepts Uncle Bob calls Clean architecture, and you can find more useful resources searching for this.


问:
Linking two or more different programming languages
I would like to ask how optimizer software written in C/C++ can be linked to simulator software written in FORTRAN or any other language. I have copied the section of journal article of Singh and Chakrabarty (2011).

In the present study, MODFLOW 2000 and MT3DMS 5.0 are
  linked as independent modules with the optimization code.
  Modifications are made to the codes of the simulators in such a
  way that they can be run through input files, and both of them
  are then compiled. One of the files required to run MODFLOW
  2000 is prepared by the optimization algorithm. This file contains
  the latest values of the decision variables. The NSGA II separately
  calls both MODFLOW 2000 and MT3DMS 5.0 in their compiled
  forms as independent modules. MODFLOW 2000 uses the file
  prepared by NSGA II to calculate hydraulic head and prepare
  an output file containing these values. Similarly, MT3DMS 5.0 calculates
  contaminant concentrations at selected locations and produces
  an output file containing the concentration values. The output
  files produced by the simulators are used by NSGA II as input files
  to produce updated values of the decision variables. The optimization
  problem, thus, runs until convergence. Obviously, writing of
  interface programs for linking codes written in different languages
  is altogether eliminated in this technique of linking.

I believe from here I can move forward with my research.
Thanks to you all.

答:
It sounds like you are saying each of the simulator programs is a separate executable, and you run it by 1) writing a file for it to input, 2) spawning a process to run it and waiting for it to complete, and 3) reading its result file.
As they say, in this way the various modules can be written in any language, it doesn't matter what languages.

The problem with this approach is performance.
If it takes longer to execute than you want to wait, chances are you will find, if you use this technique, that a quite large fraction of time is spent in each of the three steps - writing, spawning, and reading.
If so, that implies the execution time could be reduced by a big factor.

Compilers like gcc and gfortran play together nicely, as @Basile points out.
If the various tools can be compiled and linked together into a single executable, and communicate directly through in-memory data passing, eliminating the need for file formatting and parsing, and eliminating the need for process startup, you may find it a big speedup.
Possibly one or two orders of magnitude.


问:
Optional features: default method or separated interface
Dedicated interfaces seems to be a good way to expose the optional features in a domain-specific type hierarchy. However, they impede the use of decorator and composite patterns, which is also common in this kind of hierarchy.

Especially, probably no one wants to implement a decorator/composite for each possible combination of these interfaces, so more often than not they implements all optional interfaces and use type checking to selectively forward the calls, which defeats the purpose of having separated interfaces.

An alternative, which the Java Collection framework uses, is to include all operations in the base type and just fill them with dummy implementations. Default methods in Java 8 further facilitates this usage.

In a way, this feels like the nullable columns debate in the database world. Is there any strong argument against the more practical latter approach?

答:
One solution to this problem I've used in the past (where a large number of decorators add facilities to a relatively simple base, with many possible interfaces) is to have a base class for both the decorators and the classes they wrap, regardless of interface they implement, that has a method declared (using Java's syntax):

```<code>    public <T> T findImplementation (Class<T> cls) {
       if (cls.isAssignableFrom(getClass())
           return cls.cast(this);
      return wrapped.findImplementation (cls);
   }
</code>```

Obviously non-decorator implementations return null rather than passing the request on, as there's nowhere to pass it in this case.

Body:
One solution to this problem I've used in the past (where a large number of decorators add facilities to a relatively simple base, with many possible interfaces) is to have a base class for both the decorators and the classes they wrap, regardless of interface they implement, that has a method declared (using Java's syntax):

    public <T> T findImplementation (Class<T> cls) {
       if (cls.isAssignableFrom(getClass())
           return cls.cast(this);
      return wrapped.findImplementation (cls);
   }

Obviously non-decorator implementations return null rather than passing the request on, as there's nowhere to pass it in this case.


问:
When is an object passed to a function?
Trying to clearly state the semantics of a function call.

In calling a function, are the arguments passed to the function the ones the calling code initially gives or the ones the function receives?

With code like below, the calling code in bar() calls foo() twice.  This first time with int 2, then ...

1) Function foo() is called with a double 3.1, x has the converted value of int 3,

or

2) The value double 3.1 is converted to int 3 and function foo() is called,

or

3) Something else.

IOWs, is the conversion of double 3.1 to int 3 part of the call of a function (the conversion would not happen without the function call) or is it a preceding activity (consider to be part of the calling code) before the function call?

```<code>void foo(int x);

void bar() {
  foo(2);
  foo(3.1);
}
</code>```

This query is primarily C, yet language agnostic thoughts appreciated.  A quick answer is not needed.

[Edit]

Note: This is not an question of how platforms create the binary/executable to implement the program code - just about the code/language.

[Edit 2]
@ Erik Eidt useful comment provided better words to use (at least for C) for this question.

Perhaps a more succinct question would be, from the language perspective: "Are functions called with "actual arguments" or "formal parameters"?

C11 3.3 actual arguments and 3.16 1 formal parameter.

答:
Conversion is always done by the calling code, not in the called function (in particular because types get erased at runtime: the implementation does not know about types at runtime,  only at compile-time). A C function which is declared (at least those which are not variadic, e.g. without ... ending there argument type list, like printf) has a well defined signature, given by its prototype.

Practically, every called function should have a prototype these days, often provided in some header file.

This is covered by §6.5.2.2 Function Calls of the standard (citing the n1570 draft of C11 standard, paragraph 7):

If the expression that denotes the called function has a type that does include a prototype,
       the arguments are implicitly converted, as if by assignment, to the types of the
       corresponding parameters, taking the type of each parameter to be the unqualified version
       of its declared type.

So your case 2 apply.

Practically speaking, on many implementations of the C standard, the ABI document specifies the calling conventions. Read as an example the SVR4 ABI for x86-64. Often, arguments (at least the first few ones) are passed in registers, and different registers are used for int formals and for double ones. Since you gave a prototype for foo its int argument is required to be passed by the %rdi register (and %xmm0 would be used to pass a float formal argument) so the calling code in the caller function would load that integer register (perhaps by converting a float value).

BTW, in your example foo(3.1) the conversion to 3 is likely to be optimized by the compiler at compile time (constant folding) so the compiler would very probably emit the same assembler code as for foo(3) since you declared with a prototype void foo(int x); before the call.

If using GCC you should compile some simple sample code in file foo.c with gcc -fverbose-asm -Wall -O -S foo.c and look into the generated assembler file foo.s

There are some languages (like Common Lisp, Scheme, Perl, Python, Ruby) with dynamic typing. Then, each value knows its type (it is often represented in machine as some aggregate or structure with some of the fields giving the type) and your question does not really make any sense (you could understand that these language implementations handle only one value type, which would be a tagged union).

Title: When is an object passed to a function?


答:
In C++ you have function overloading, that is given a series of functions with the same name but different input parameters (the return value is not considered) the compiler must look for the better pick, taking into account implicit conversions and namespace resolution.

So functionally the compiler finds a function call with a given input, and then looks if some overload fits the bill.

There could be well be more than one possible eligible overload, so it tries to find the best one which is then called.

In this sense the conversion is done before calling, since at first you don't even know which function to call.

Title: When is an object passed to a function?

Body:
Trying to clearly state the semantics of a function call.

In calling a function, are the arguments passed to the function the ones the calling code initially gives or the ones the function receives?

With code like below, the calling code in bar() calls foo() twice.  This first time with int 2, then ...

1) Function foo() is called with a double 3.1, x has the converted value of int 3,

or

2) The value double 3.1 is converted to int 3 and function foo() is called,

or

3) Something else.

IOWs, is the conversion of double 3.1 to int 3 part of the call of a function (the conversion would not happen without the function call) or is it a preceding activity (consider to be part of the calling code) before the function call?

```<code>void foo(int x);

void bar() {
  foo(2);
  foo(3.1);
}
</code>```

This query is primarily C, yet language agnostic thoughts appreciated.  A quick answer is not needed.

[Edit]

Note: This is not an question of how platforms create the binary/executable to implement the program code - just about the code/language.

[Edit 2]
@ Erik Eidt useful comment provided better words to use (at least for C) for this question.

Perhaps a more succinct question would be, from the language perspective: "Are functions called with "actual arguments" or "formal parameters"?

C11 3.3 actual arguments and 3.16 1 formal parameter.


问:
Does music increase your productivity?
I wanted to know whether you think and audio background is just a distraction or could be of some help while programming.

For me, it works like this:

when I'm writing pseudocode, or implementing procedures that are very clear in my mind in a language I can write without looking up docs, having music playing in the background (very straightforward electronics, mostly) helps me a lot: it kind of gives some rhythm to my coding and, if the procedures are trivial, avoids the distractions that boredom can cause.

When I incur in a problem, or I have to try to fix a bug, instead, it just distracts me.

Also, if the song is really regular and I know it well enough not to cause me to focus on it, it eliminates unexpected environmental noise that sometimes make me waste precious seconds before I can concentrate on the code again.

Guidelines checklist: 1 ok, 2 I hope; 3 I suppose; 4 Definitely; 5 I would like that to happen; 6 Doch (English should implement a way to disambiguate double negatives in answers)

答: As you said, it all depends on whether you can focus better with or without the music. If I am in an environment that is noisy then I find music does help, although generally I prefer not to listen to music while working on code.</p>

Title: Does music increase your productivity?


答:
I never could remember which is "big-endian" and which is "little-endian" but knew the endianness of PowerPC and Intel x86 processors. Little has most of the letters in common with Intel, so Intel x86 is little-endian. </p>

<p>Of course that's only useful if you know the byte order of PPC and x86. On the other hand, you should now remember that Intel x86 = little-endian. And remember that x86 and ARM are very, very compatible even with totally different instruction sets. </p>

Title: Is there any practical trick to remember the difference between big-endian and little-endian?

Body:
I don't work every day with big-endian and little-endian problems and thus I find very difficult to remember which one is what.

Recently I got an interview asking the difference between the two; since I didn't remember I decided to "guess" (50% chance, after all) but I failed.

So, is there any wide known pratical trick to remember what is the difference between big endian and little endian?

Body:
I never could remember which is "big-endian" and which is "little-endian" but knew the endianness of PowerPC and Intel x86 processors. Little has most of the letters in common with Intel, so Intel x86 is little-endian.

Of course that's only useful if you know the byte order of PPC and x86. On the other hand, you should now remember that Intel x86 = little-endian. And remember that x86 and ARM are very, very compatible even with totally different instruction sets.


问:
Combining Fitnesse, .NET and RESTful APIs
I know there is Fitsharp for combining Fitnesse and .NET. And there is RestFixture to combine Fitnesse and REST.

Is there a way to test a RESTful service with Fitnesse under .NET?

If not, is there a different way to perform integration testing on web services?

答: As it turns out, I was viewing it from the wrong perspective. I can build my webservice with any programming language I like, deploy it on some test server and test it with Fitnesse and RestFixture. No problems.</p>


问:
Help understanding modeling in domain-driven design
I've been trying to learn domain-driven design (and similarly Onion Architecture) the last week or so. I think I've got an understanding of it, but like math, I suck at extracting all of the details...

So, I'm designing/building an ASP.NET MVC application (building a site to promote game jams), applying DDD to the project. I've read all of Vaughn Vernon's essay (just discovered the book).

However, I'm a bit hung up about my particular project's domain model. Conceptually, I think I have one bounded context within my domain. I'm not sure if you include web users (ASP.NET Identity I plan on using).

Here's my current (prototype) model (currently one bounded context):

Another bounded context I can foresee later, but I think it's more in-tune with the infrastructure (thinking Onion here), is the User (linked with 'Developer' on the above bounded context) authentication. I have two 'value objects' ("Developer" and "Description"). I'm unsure whether "Description" should be just a simple string on the entity "Project" though.

Thinking about my invariant behaviors, I've come up with the following:

An event is created by a Developer (using a role for this) with a start and end dates.

Teams are created a Developer for an event.

A team creates a project for an event

Developers sign-up for an event through a project(s) by applying

Developers can join multiple projects

applying: providing the team leader with a developer's name and role in which they are seeking on a project.

Teams can be created as either open (Developers can apply to join) or closed (team leader must invite a Developer to the team/project)

For my aggregates, what do I do here? Do I write a "service" class like "TeamProjectService" with methods such as "CreateTeamProject"? Or what?

Am I going about this the right way? Or am I maybe over-complicating it or missing something?

答:
Am I going about this the right way? Or am I maybe over-complicating it or missing something?

I think you have a start of a design; you are teasing out the concepts and their basic relationships and the constraints on the relationships, which is a great start.

For me, what I like to do is before I do any real detail on classes and operations (e.g. what methods, where business logic goes), I like to lightly enumerate the concepts and relationships in the business terms that create the ubiquitous language for a domain model.  The concepts that have business identities (e.g. plane ticket with record locator, user having unique user name or id, etc...) will probably end up being aggregate roots.  Ideally, these concepts and relationships are already known in the business and one doesn't have to try reinvent them as part of design. (And of course, iteration, improvements, refactoring, etc... will occur.)

Next, for me personally, having a good start at the concepts and relationships, I like to do application design from the ends toward the middle.  I think of it a bit like designing a bridge.  I like to have a design for the embankments first, then the middle (the span).  In this analogy one embankment end is the persistence implementation, where I'm thinking about modeling concepts and also their relationships and some of their constraints with SQL using tables.  The other end is the externally exposed interface, where I'm thinking about a REST API using OData principles.

I then design the classes, methods, and operations as a bridge that spans between the two, now-known embankments.  Also note that we have many choices when it comes to class design (e.g. to use ORM or not, which classes get which methods and where business & application logic go), as the classes in the middle are closer to internal implementation and farther from externally exposed API.

I think you will want a formal notion of different kinds of Users (in addition to Developer), such as Business Stake Holder -- they might be the ones to initiate Projects.

The term event is overused in our business, so I try to use it only in a narrow way (my opinion is that an "event" is something that happened, once, either just now or in the past, and events can fire, be subscribed to, etc...).  So, you might choose a more specific name within your business domain for what you are calling event.  On the other hand, I'd probably move in the direction of more general recursively composed projects, so projects can compose/decompose into any number of other projects.  You already have several specific layers of composition: Event, Project, Application, why not get more general?  Yet still, recursive composition may not suffice, you may also need to track dependencies between projects (e.g between peer sub projects, or independent project that are not composed).  I might try to formalize the notion of schedule along with notions of dependency.

For my aggregates, what do I do here? Do I write a "service" class like "TeamProjectService" with methods such as "CreateTeamProject"? Or what?

I have two comments here.

First, I would tend to think about the items you list in bold as aggregate roots as they probably have solid identities externally referable from outside the aggregate.  Aggregate roots can be related to other aggregate roots (and for NxM relations I would model persistence for each of those with their own first-class table).  The way you are using the term aggregate above makes me think about the relationships between aggregate roots more than the entities within the aggregate.

Second, I would probably do relationship creation via an operation attached to one or both of the aggregate roots being related.  For example, a team entity might be able to create a project, or the project collection could create a project though requiring a team as a parameter.

These days, I like to use OAuth2 (e.g. Windows Live, Facebook, Google+, Twitter, Stackoverflow) for authentication (I do OAuth2 directly but perhaps Azure ACS can help abstract this across the variety of OAuth2 providers).


问:
What exactly is interface compliance in C++?
I was reading this. It says that

Some people believe that the purpose of inheritance is code reuse. In
C++, this is wrong. Stated plainly, “inheritance is not for code
reuse.”

The purpose of inheritance in C++ is to express interface compliance
(subtyping), not to get code reuse. In C++, code reuse usually comes
via composition rather than via inheritance. In other words,
inheritance is mainly a specification technique rather than an
implementation technique.

So, my question is what exactly interface compliance(subtyping) in C++? How inheritance is used to express it? How subtyping & subclasses are different? It would be better if someone answers it by giving suitable real world example.

答:
Rather than having a reusable code, you have a code which is interchangeable.

A real life example using the DI and Adapter patters. Let's say you have a class, which handles data. It does not retrieve the data, but handles it. We could simply call it DataHandler.

```<code>class DataHandler
{
public:
    void doSomethingWithData() {}
protected:
private:
};
</code>```

When you start using the DataHandler in your app, you use it to handle data from a SQL Database. So the DataHandler will need an instance of said class.

```<code>class SqlDatabaseDataRetriever
{
public:
    Data getData() { }
protected:
private:
};

class DataHandler
{
public:
    DataHandler(SqlDatabaseDataRetriever& dataRetriever)
    {
        _dataRetriever = dataRetriever;
    }

    void doSomethingWithData()
    {
        Data data = this->_dataRetriever.getData();
    }
protected:
    SqlDatabaseDataRetriever _dataRetriever;
private:
};
</code>```

But what if later you decide, you don't want to access the database directly via SqlDatabaseDataRetriever, so you create an API and you create new class which is used to handle the request via your API and retrieves data from it.

So we want to use the DataHandler class with our new ApiDataRetriever, but currently our DataHandler uses a different class. You could just rewrite your code, inject the ApiDataRetriever instead, but there's a better solution.

You will create an abstract class, which all your DataRetrievers will inherit, you will inject this abstract class instead and use it's methods.

```<code>class DataRetriever
{
public:
    virtual Data getData() = 0;
protected:
private;
}

class SqlDatabaseDataRetriever : public DataRetriever
{
public:
    virtual Data getData() { }
protected:
private;
}

class ApiDataRetriever : public DataRetriever
{
public:
    virtual Data getData() { }
protected:
private;
}

class DataHandler
{
public:
    DataHandler(DataRetriever& dataRetriever)
    {
        _dataRetriever = dataRetriever;
    }

    void doSomethingWithData()
    {
        Data data = this->_dataRetriever.getData();
    }
protected:
    DataRetriever _dataRetriever;
private:
};
</code>```

Because the function in parent class is defined as pure virtual, it has to be implemented in child class, and because you are injecting the parent class, but that cannot be instantiated, you will always get a subject class having the parent method, which you can use without constraints.

Body:
Rather than having a reusable code, you have a code which is interchangeable.

A real life example using the DI and Adapter patters. Let's say you have a class, which handles data. It does not retrieve the data, but handles it. We could simply call it DataHandler.

class DataHandler
{
public:
    void doSomethingWithData() {}
protected:
private:
};

When you start using the DataHandler in your app, you use it to handle data from a SQL Database. So the DataHandler will need an instance of said class.

class SqlDatabaseDataRetriever
{
public:
    Data getData() { }
protected:
private:
};

class DataHandler
{
public:
    DataHandler(SqlDatabaseDataRetriever& dataRetriever)
    {
        _dataRetriever = dataRetriever;
    }

    void doSomethingWithData()
    {
        Data data = this->_dataRetriever.getData();
    }
protected:
    SqlDatabaseDataRetriever _dataRetriever;
private:
};

But what if later you decide, you don't want to access the database directly via SqlDatabaseDataRetriever, so you create an API and you create new class which is used to handle the request via your API and retrieves data from it.

So we want to use the DataHandler class with our new ApiDataRetriever, but currently our DataHandler uses a different class. You could just rewrite your code, inject the ApiDataRetriever instead, but there's a better solution.

You will create an abstract class, which all your DataRetrievers will inherit, you will inject this abstract class instead and use it's methods.

class DataRetriever
{
public:
    virtual Data getData() = 0;
protected:
private;
}

class SqlDatabaseDataRetriever : public DataRetriever
{
public:
    virtual Data getData() { }
protected:
private;
}

class ApiDataRetriever : public DataRetriever
{
public:
    virtual Data getData() { }
protected:
private;
}

class DataHandler
{
public:
    DataHandler(DataRetriever& dataRetriever)
    {
        _dataRetriever = dataRetriever;
    }

    void doSomethingWithData()
    {
        Data data = this->_dataRetriever.getData();
    }
protected:
    DataRetriever _dataRetriever;
private:
};

Because the function in parent class is defined as pure virtual, it has to be implemented in child class, and because you are injecting the parent class, but that cannot be instantiated, you will always get a subject class having the parent method, which you can use without constraints.


问:
What does your Technical Documentation look like?
I'm working on a large project and I would like to put together some technical documentation for other members of the team and for new programmers joining the project.

What sort of documentation should I have? Just /// code comments or some other file(s) explaining the architecture and class design?

I've never really done documentation except the occasional word doc to go with smaller apps, and I think this project is too large to doc in a single word file.

答:
I would strongly recommend you to go through doxygen and edit your source files appropriately. Then run doxygen and it'd generate enough technical documentation like class hierarchy etc.

In fact make doxygen a part of the build process, and keep following the commenting convention as you go.

Just the architecture and class design alone is not good enough for big projects. Here's the minimum:

Please document global variables. No exceptions.

If a function is modifying anything other than its inputs, please specify the same.

Any non-trivial stuff that some routine is doing. Particularly, if you are implementing some complex algorithm, include a reference to that algorithm url or paper.

Known hacks that you put in and had promised yourself to fix it over the weekend.


答:
A subtype is a type which fulfills the contract of a basetype.

A subclass is a class which inherits from a baseclass.

In C++ (disregarding templates) you can only create a subtype by subclassing, which gives the compiler lots of additional information useful for optimization and static checking.

The same cannot be said about objective-c, where a subtype only needs to handle the messages the basetype understands the same way: Duck-typing "If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck."

C++ templates are also duck-typing (types must have appropriate members), though completely at compile-time and thus not incurring any of the penalties of dynamic typing.

An example of sub-typing without sub-classing would be using standard algorithms:

```<code>template<class T> void sortall(T& x) {
    using std::begin;
    using std::end;
    std::sort(begin(v), end(v));
}
</code>```

Which can be called whether the argument is a std::vector, a std::array or some other container, even though none of the examples are related by inheritance.

While sub-classing without sub-typing is possible by ignoring the inherited contract, that's a sin one simply should abstain from committing.

Title: What exactly is interface compliance in C++?

Body:
I was reading this. It says that

Some people believe that the purpose of inheritance is code reuse. In
C++, this is wrong. Stated plainly, “inheritance is not for code
reuse.”

The purpose of inheritance in C++ is to express interface compliance
(subtyping), not to get code reuse. In C++, code reuse usually comes
via composition rather than via inheritance. In other words,
inheritance is mainly a specification technique rather than an
implementation technique.

So, my question is what exactly interface compliance(subtyping) in C++? How inheritance is used to express it? How subtyping & subclasses are different? It would be better if someone answers it by giving suitable real world example.

Body:
A subtype is a type which fulfills the contract of a basetype.

A subclass is a class which inherits from a baseclass.

In C++ (disregarding templates) you can only create a subtype by subclassing, which gives the compiler lots of additional information useful for optimization and static checking.

The same cannot be said about objective-c, where a subtype only needs to handle the messages the basetype understands the same way: Duck-typing "If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck."

C++ templates are also duck-typing (types must have appropriate members), though completely at compile-time and thus not incurring any of the penalties of dynamic typing.

An example of sub-typing without sub-classing would be using standard algorithms:

template<class T> void sortall(T& x) {
    using std::begin;
    using std::end;
    std::sort(begin(v), end(v));
}

Which can be called whether the argument is a std::vector, a std::array or some other container, even though none of the examples are related by inheritance.

While sub-classing without sub-typing is possible by ignoring the inherited contract, that's a sin one simply should abstain from committing.


问:
why use postfix /prefix expression instead of infix?
I understand how to convert infix to postfix/prefix but I do not understand why postfix or prefix expression are used in computer system?

What is the advantage of postfix prefix over infix expression?

答:
Both pre- and postfix have basically the same advantages over infix notation. The most important of these are:

much easier to translate to a format that is suitable for direct execution. Either format can trivially be turned into a tree for further processing, and postfix can be directly translated to code if you use a stack-based processor or virtual machine

entirely unambiguous. Infix notation requires precedence and associativity rules to disambiguate it, or addition of extra parentheses that are not usually considered part of the notation. As long as the number of arguments to each operator are known in advance, both prefix and postfix notation are entirely unambiguous: "* + 5 6 3" is (5+6)*3, and cannot be interpreted as 5+(6*3), whereas parenthesis is required to achieve with infix.

supports operators with different numbers of arguments without variation of syntax. "unary-op 5" and "ternary-op 1 2 3" both work fine, but need special syntax to make them work in infix.


问:
Event Sourcing , sagas, bus and eventual consistency
I am currently learning about Event Sourcing via the book Microsoft .NET - Architecting Applications for the Enterprise. Event sourcing is, in my own words, an architectural pattern of storing "events" instead of "current entities". Current entities can be created by looping over the events belonging to it.

The problem of performance of creation of current entities can be mitigated by creating an extra storage where periodically the current entities are "snapshotted" (created from the previous snapshot and the events that happened after it).

In the book the architecture belonging to Event Source is setup as follows:

Here all events (related to a Waterpolo match) are stored in a NoSQL RavenDB store. We also see a bus to keep track of events and a saga which belong to groups of events.

I have a few questions about Event Sourcing (I decided to ask them all at once since all questions relate to the description in the book):

I am wondering in what way these events would be stored. I can imagine that the data in events can change over time (extra properties, new event names) and that events need to be easily related to each other and itself. How does the actual structure of the database and data access code look to facilitate change and data retrieval?

What is a saga? Why is it called a saga? Are they persisted and if so, how?

How does a bus work? What are the advantages over just writing events directly to an event store?

In the above architecture where commands and queries are separated (CQRS) and the commands are implemented using Event Sourcing while queries read from the snapshot, what happens when data needs to be displayed during the initiation of a command? (E.g., showing bank account data while a user wants to make a deposit, based on this data.) How, in practice, do we make sure the data displayed is up to date?

答:
Event storage

Event storage will depend on your application but it is a lot easier if you use a flexible storage for your events (so a NoSQL DB, JSON or XML). How you deal with updates will depend on several factors you need to take into account such as requirements for availability and timeframes for updates, amount of events, etc...

Update your events when your application updates: as part of the deployment of a new application, update all your previous events to the new schema

Version your events: have a version-id on your event. When an event is read from the database some piece of code knows how to 'upgrade' older events to the current structure. Like the first option, but basically 'on demand'

Throw away your old events: when your application updates, make a snapshot of all entities and throw away (or archive) the old events.

Never throw away old events: basically keep 'PurchaseOrder' forever. When you need another field, use a new event such as 'PurchaseOrderWithCouponCode'.

Saga's

A saga is basically a long-running event chopped up into pieces. This might be due to different reasons: it could be because you want to have an action that results in multiple events handled in parallel to avoid blocking with a transaction, because you need to coordinate several external systems, or because you need to coordinate with events that cross a bounded context. You need to persist them because of that reason: a saga can be started, launch a few events and at some non-deterministic point can have to resume by launching more events. Udi Dahan has a good introduction on this.

Message buses

There is a lot that can be said about buses. They abstract a large part of the storage of events for you and can handle more complicated scenario's, for example when you have multiple applications that need to work with the event store. For small applications you can write directly into the event store (and the code that would do that could be considered a bus...)

Data up to date

Short answer: you don't. Event sourcing works around this in several ways because you are 'eventually consistent'. In this example, you could simply display a message to the users that it might take up to ten minutes for deposits to show up...


问:
I don't know C. And why should I learn it?
My first programming language was PHP (gasp).  After that I started working with JavaScript.  I've recently done work in C#.

I've never once looked at low or mid level languages like C.

The general consensus in the programming-community-at-large is that "a programmer who hasn't learned something like C, frankly, just can't handle programming concepts like pointers, data types, passing values by reference, etc."

I do not agree. I argue that:

Because high level languages are easily accessible, more "non-programmers" dive in and make a mess

In order to really get anything done in a high level language, one needs to understand the same similar concepts that most proponents of "learn-low-level-first" evangelize about.

Some people need to know C; those people have jobs that require them to write low to mid-level code. I'm sure C is awesome, and I'm sure there are a few bad programmers who know C.

Why the bias?  As a good, honest, hungry programmer, if I had to learn C (for some unforeseen reason), I would learn C.  Considering the multitude of languages out there, shouldn't good programmers focus on learning what advances us? Shouldn't we learn what interests us?  Should we not utilize our finite time moving forward?  Why do some programmers disagree with this?

I believe that striving for excellence in what you do is the fundamental deterministic trait between good programmers and bad ones.

Does anyone have any real world examples of how something written in a high level language—say Java, Pascal, PHP, or JavaScript—truly benefited from a prior knowledge of C? Examples would be most appreciated.

答:
I guess this is progress.

Twenty years ago, the conventional wisdom was that you had to learn assembler in order to understand what you were gaining from higher-level languages like C (which is why I had to take an assembler class in college using VAX Macro; guess how useful that turned out to be upon graduating).

There's a superstition that because C is somewhat hard to learn and that it provides almost no abstractions (pointers and byte streams are pretty much it), learning it will somehow make you a better programmer or give you greater insight into how things work at the hardware level.

This is not (necessarily) true.  Standard C doesn't get you any closer to the metal than any other 3GL (Pascal, Fortran, etc.).  Some C implementations may provide hooks that give you greater access to some areas, but in general naked pointers are about as close as you get, which isn't close at all.  You cannot directly access registers or status words, for example.

In the end, it all comes down to opcodes and addressing modes, so if you're really interested in how things work at the lower level, you'd be better served learning assembler over C.

By itself, learning C will not (necessarily) make you a better programmer.  It will definitely give you an appreciation for actual string types and standardized container libraries, though.


问:
Relating an array of objects to an enumerator
How would you relate the indexes of an array to an enumerator without leaving the chance of mismatch? Example

```<code>public enum difficulties {
   easy,
   medium,
   hard
}

public List<Lobby> easyLobbies = new List<Lobby>();
public List<Lobby> mediumLobbies = new List<Lobby>();
public List<Lobby> hardLobbies = new List<Lobby>();

public List<Lobby>[] lobbiesArray;

public ClassConstructor(){
    // Index order should match enumerator
    lobbiesArray = new List<Lobby>[] { easyLobbies, mediumLobbies, hardLobbies};
}

List<Lobby> lobbies = lobbiesArray[difficulties.hard];
</code>```

Because this enumerator and array are seemingly unlinked, it is not obvious that the lobbiesArray should follow any order. What is a better way to approach this?

答:
You are using a wrong data structure.

In your case, you may use a dictionary where keys are the values from the enum, and the values are the actual lists:

```<code>var lobbies = new Dictionary<Difficulty, List<Lobby>>
{
    { Difficulty.Easy, easyLobbies },
    { Difficulty.Medium, mediumLobbies },
    { Difficulty.Hard, hardLobbies },
};

var currentLobbies = lobbies[Difficulty.Hard];
</code>```

A few notes:

An array is mostly always a wrong data structure in C#. Don't use it, unless you are perfectly certain that you need the specific characteristics of an array.

Unless your team has a well-established style convention (and the inconsistencies in your code makes me think that there are none), stick with the standards. This means that enum Difficulties, with a capital D. The members of an enum start with a capital too. You can use StyleCop to check for other violations (like the lack of a new line before the opening curly bracket.)

Since your enum doesn't contain flags, its name should be Difficulty, not Difficulties. When you use plural, it means that you can use multiple values at once. More on flags here.

lobbiesArray is a wrong name. You shouldn't have types in the names of the variables. Visual Studio makes it very easy to determine the type of a given variable, so you don't need Hungarian notation or similar constructs.

ClassConstructor is a misleading name for a method, because it makes the reader think that it's an actual constructor, while it's not (unless you actually called your class ClassConstructor, which is a strange name for a class.)

Body:
You are using a wrong data structure.

In your case, you may use a dictionary where keys are the values from the enum, and the values are the actual lists:

var lobbies = new Dictionary<Difficulty, List<Lobby>>
{
    { Difficulty.Easy, easyLobbies },
    { Difficulty.Medium, mediumLobbies },
    { Difficulty.Hard, hardLobbies },
};

var currentLobbies = lobbies[Difficulty.Hard];

A few notes:

An array is mostly always a wrong data structure in C#. Don't use it, unless you are perfectly certain that you need the specific characteristics of an array.

Unless your team has a well-established style convention (and the inconsistencies in your code makes me think that there are none), stick with the standards. This means that enum Difficulties, with a capital D. The members of an enum start with a capital too. You can use StyleCop to check for other violations (like the lack of a new line before the opening curly bracket.)

Since your enum doesn't contain flags, its name should be Difficulty, not Difficulties. When you use plural, it means that you can use multiple values at once. More on flags here.

lobbiesArray is a wrong name. You shouldn't have types in the names of the variables. Visual Studio makes it very easy to determine the type of a given variable, so you don't need Hungarian notation or similar constructs.

ClassConstructor is a misleading name for a method, because it makes the reader think that it's an actual constructor, while it's not (unless you actually called your class ClassConstructor, which is a strange name for a class.)


问:
Unnamed member access?
I'm trying to understand this piece of C++ code from a text book:

```<code>template<typename T, int N>
struct Buffer {
  using value_type = T;
  constexpr int size() { return N; }
  T[N];
  // ...
};
</code>```

It demonstrates stack allocation of the T[N] array, but the array is not named. Later in the text this declaration is made:

```<code>Buffer<int,10> buf;
</code>```

but it's not clear how to access the array buried inside this struct. Does the //... have to include some accessors or is there some implicit facility of the language that can be used to get at the ints[10] that live within buf?

答:
Maybe there some mistake, code does not even compile. So correct code would be like

```<code>template<typename T, int N>
struct Buffer {
using value_type = T;
constexpr int size() { return N; }
T b[N];
// ...
};
</code>```

Edit: I tested it using gnu gcc 4.7.1 compiler in c++11 mode.

Title: Unnamed member access?

Body:
Maybe there some mistake, code does not even compile. So correct code would be like

template<typename T, int N>
struct Buffer {
using value_type = T;
constexpr int size() { return N; }
T b[N];
// ...
};

Edit: I tested it using gnu gcc 4.7.1 compiler in c++11 mode.


答:
In my case when i listen to music using noice canceling headphones it helps me concentrate a lot. When the melody is regular, it feels like being in a bubble.
I dont have an office for my own so it could get quite crowded in there.</p>

Title: Does music increase your productivity?

Body:
I wanted to know whether you think and audio background is just a distraction or could be of some help while programming.

For me, it works like this:

when I'm writing pseudocode, or implementing procedures that are very clear in my mind in a language I can write without looking up docs, having music playing in the background (very straightforward electronics, mostly) helps me a lot: it kind of gives some rhythm to my coding and, if the procedures are trivial, avoids the distractions that boredom can cause.

When I incur in a problem, or I have to try to fix a bug, instead, it just distracts me.

Also, if the song is really regular and I know it well enough not to cause me to focus on it, it eliminates unexpected environmental noise that sometimes make me waste precious seconds before I can concentrate on the code again.

Guidelines checklist: 1 ok, 2 I hope; 3 I suppose; 4 Definitely; 5 I would like that to happen; 6 Doch (English should implement a way to disambiguate double negatives in answers)


问:
How do you avoid dominant solutions in multi-objective simulated annealing?
Imagine an RPG game were you can cary N items, and you want to maximise your damage, attack speed and armour, given a set of items.

I implemented simulated annealing where a permutation simply replaces a random item, and I compute the energy with some damage calculations.

This works well for attack speed and damage, and tends to find items that provide both. But adding armour never gives good results.

I have tried a weighted sum, but the result is always N armour items or N weapons.

This paper suggests picking a random or average energy function, but this gives very bad results as soon as I use conflicting objectives.

Are there good probability functions for this task, or should I use another algorithm?

答:
Everyone who said your utility function needs to track the actual problem domain is correct.  Here’s my advice on how, specifically, to do that.

The utility of weapons and armor in a D&D-like RPG is that they help you win battles.  How useful at the margin better armor or a better weapon are is going to depend on what you’re fighting: more damage is useless if you already are killing a goblin with every hit, for example.  So you need to come up with a reasonable list of encounters and a way to estimate how good a kit is against each encounter.  This probably means calculating how likely you are to hit that opponent, how likely it is to hit you, and how much of the other’s health each of you will knock off with each hit.  If you hit 80% of the time for 20 points of damage and it has 50 health, you’d expect, on average, to need 2.5 hits to kill it and 3.125 rounds to get those 2.5 hits.

The ratio of expected-rounds-for-you-to-kill-it to expected-rounds-for-it-to-kill-you is probably a good heuristic to use in a combat system derived from D&D, and you can probably figure it out with some basic statistics, but it can fail in some situations: it really doesn’t help you to do 90% damage instead of 51% if you’ll still need two hits to kill it.  A more complex alternative would be to calculate instead how likely you are to win the fight.  First calculate how likely the opponent is to die in one hit, two, three and so on; then how likely you are to have one hit on the first round, one hit on the second, two hits on the second, and so on, up to a reasonable number of rounds.  Repeat for its attacks on you, and you can calculate the odds that each of you will die on each round.

For a much more complicated combat system, where generating a probability tree would be infeasible, you might need to do some Monte Carlo simulations of battles to get an accurate optimization.

The simple heuristic you want, though, is probably something like, (YourChanceToHit * YourDPS * YourHealth) / (TheirChanceToHit * TheirDPS * TheirHealth).  That captures the intuition that the following are roughly equivalent: hitting twice as often, needing half as many hits to kill them, getting hit half as often, or surviving twice as many hits.


答:
Relating an array of objects to an enumerator

Do you mean relating an array of objects to an enum?

If so then how about this ...

it is not obvious that the lobbiesArray should follow any order.

Make it obvious by implementing; Lobby : IComparable, using the enum. The declared order in the enum is relevant

```<code>public int CompareTo(object other) {
    if(other == null) return 1;
    if(!other is Lobby) return 1;
    if((int)this.Difficulty > (int)other.Difficulty)) return 1;
    if ((int)this.Difficulty < (int)other.Difficulty)) return -1;
    return 0;
}
</code>```

Then the following will sort/group by enum order:

```<code>myLobbies.Sort();
</code>```

If List<Lobby> must be sub-sorted then modify CompareTo to include all the needed properties.

To make it further obvious about the enum I would drop the array and implement a LobbyCollection.

```<code>public class LobbyCollection {
    protected List<Lobby> Lobbies;

    // pretend we have constructor and Add method(s) as needed

    // might want to return a LobbyCollection instead.
    public List<Lobby> GetLobbies(Difficulty ofThisDifficulity) {
        return this.Lobbies.FindAll(aLobby => aLobby.Difficulty == ofThisDifficulty);
    }
}
</code>```

So the enum declarations, interface implementation, and LobbyCollection exposing only defined Lobby behavior together make it obvious how to use a Lobby.  And clients don't have to make up stuff - with different client code likely doing things just ever so slightly differently.

Body:
How would you relate the indexes of an array to an enumerator without leaving the chance of mismatch? Example

```<code>public enum difficulties {
   easy,
   medium,
   hard
}

public List<Lobby> easyLobbies = new List<Lobby>();
public List<Lobby> mediumLobbies = new List<Lobby>();
public List<Lobby> hardLobbies = new List<Lobby>();

public List<Lobby>[] lobbiesArray;

public ClassConstructor(){
    // Index order should match enumerator
    lobbiesArray = new List<Lobby>[] { easyLobbies, mediumLobbies, hardLobbies};
}

List<Lobby> lobbies = lobbiesArray[difficulties.hard];
</code>```

Because this enumerator and array are seemingly unlinked, it is not obvious that the lobbiesArray should follow any order. What is a better way to approach this?

Body:
Relating an array of objects to an enumerator

Do you mean relating an array of objects to an enum?

If so then how about this ...

it is not obvious that the lobbiesArray should follow any order.

Make it obvious by implementing; Lobby : IComparable, using the enum. The declared order in the enum is relevant

public int CompareTo(object other) {
    if(other == null) return 1;
    if(!other is Lobby) return 1;
    if((int)this.Difficulty > (int)other.Difficulty)) return 1;
    if ((int)this.Difficulty < (int)other.Difficulty)) return -1;
    return 0;
}

Then the following will sort/group by enum order:

myLobbies.Sort();

If List<Lobby> must be sub-sorted then modify CompareTo to include all the needed properties.

To make it further obvious about the enum I would drop the array and implement a LobbyCollection.

public class LobbyCollection {
    protected List<Lobby> Lobbies;

    // pretend we have constructor and Add method(s) as needed

    // might want to return a LobbyCollection instead.
    public List<Lobby> GetLobbies(Difficulty ofThisDifficulity) {
        return this.Lobbies.FindAll(aLobby => aLobby.Difficulty == ofThisDifficulty);
    }
}

So the enum declarations, interface implementation, and LobbyCollection exposing only defined Lobby behavior together make it obvious how to use a Lobby.  And clients don't have to make up stuff - with different client code likely doing things just ever so slightly differently.


答:
Notice that LISP languages (e.g. Common Lisp, Scheme, Clojure and many specific dialects inspired by them like AutoLISP, Emacs-LISP, MELT, etc...) are all using a prefix-syntax: every expression starts with a left parenthesis, then the operator, then the operands, then the right parenthesis. These expressions are called S-expressions. For example 1+2*3 is typed as (+ 1 (* 2 3)) and there is no need for operator precedence.

The advantages of such a simple syntax (probably the simplest possible one for ASTs, outside of stack languages à la Forth) include:

easy to remember syntax rule for human developers

easy and quick to parse for language implementations

easy to emit when generating code in s-expressions (from some AST representation)

ability to easily make homoiconic languages above them

ability to handle many operands (e.g. have variadic operators or functions, or functions with many formal arguments)

simple to read, once you can match a left parenthesis with its right one

The disadvantage of such syntax is a pun on the language: Lots of Insipid Stupid Parenthesis. However (believe it or not) any Lisp coder don't see the parenthesis as agressive, and uses the ability (provided by any good editor) to match parenthesis when reading code on the screen.

BTW, what is important is not to convert textual representation from e.g. infix to prefix, but to parse expressions into AST (abstract syntax trees).  Very often, an AST is a tree-like structure in memory, keeping more information that the simple syntactical shape (e.g. the source location, as a file name, line number, column number, or some type information, etc...).

Title: why use postfix /prefix expression instead of infix?

Body:
I understand how to convert infix to postfix/prefix but I do not understand why postfix or prefix expression are used in computer system?

What is the advantage of postfix prefix over infix expression?


答:
It depends who do you write the documentation for. If you write it for mates programmers, it should probably be documentation in the code, let them be commentaries or more formal doxygen-like documentation. On the other hand, if your manager or customer wants to know technical details, a list of classes and what they do won't tell them much. So in that case you might want to consider having diagrams, as well as high-level description. For end-users, you probably want some FAQ, user manual and tool tips (in case of GUI application).

In the company I work, we have no customers, and no user manuals whatsoever. But we do have both high-level documentation with rationale, goals, abstract architecture etc., we have documents with network topology, latency metrics etc. And, of course, we document the code (using Doxygen) and trips&tricks in our corporate Wiki. Aside from that, we have JIRA where you can find who is working on what, what has been done and what actions performed.

Title: What does your Technical Documentation look like?

Body:
I'm working on a large project and I would like to put together some technical documentation for other members of the team and for new programmers joining the project.

What sort of documentation should I have? Just /// code comments or some other file(s) explaining the architecture and class design?

I've never really done documentation except the occasional word doc to go with smaller apps, and I think this project is too large to doc in a single word file.


问:
Design decisions while porting a non object-oriented C program to Java
Background:
My boss made a comment on porting a C program that acts as some a simulator that communicates with a remote process through sockets to Java. He didn't assign it to me, or to anyone for that matter, it was just a project he had in mind. He showed and gave me access to the C source code file for said program so I could take a look.

Now I'm an intern in this company and haven't really been assigned something in particular so I wanted to start this project on my own and then show it to my boss.

Problem:
The C program is ~4k lines long. It consists on many global variables and functions that use those variables; I guess this is mainly to avoid passing many parameters. There are even some goto statements (yeah, also most of the codebase is from 1980). So basically my question is: should I aim to replicate the structure of the C program in a single Java class so there is a visible mapping of behavior between both? Or should I come up with
a better object oriented design that may imply the creation of many components? What would be your approach to solving this problem?

Thanks.

答:
A 4Kline long C program is a small C program. It generally needs a few weeks or months to be written by a single person. If you are familiar with the domain of the program, you should be able to understand it entirely quite quickly, and write a tiny documentation describing the design and purpose of the original program (in particular, the communication protocol implemented by it, if that protocol is not well documented).

Big programs have millions of source lines: both GCC and the Linux Kernel have more than a dozen millions of lines of source code.

So don't think of porting that program to Java but consider instead an entire rewrite. Don't try to match some parts of the C programs to some part of your Java program. Don't replicate the structure of the C program in Java (but perhaps, use similar names in your Java code, when relevant). So indeed, come up with a better object oriented design and use the facilities given by Java (in particular its standard library and containers). But keep your code small (avoid writing 10Klines of Java if possible).


问:
Why were frames removed in HTML5, but not iFrames?
Why were frames removed in HTML5, but not iFrames? After all, there is almost no difference between the two. In many instances using either of them would give the same output (pardon me if I am wrong)?</p>

答:
Framesets are often used in a way where they break the fundamental principle of the Web - that each document has a single URL. This leads to problems with linking, bookmarks, search engines etc.

The typical use of a frameset would be a frame at the top with a logo or header, a frame at the side with a menu, and a content frame. But search engines index individual pages, so when you find some page in Google, it would link directly to the content page without the frameset, so you lose the navigation. The problem with links and bookmarks is you would typically want to link or bookmark a particular content page inside the frameset, without losing the frameset itself. The is no easy way to do that.

The reason framesets became popular in the first place was because they allowed a statically positioned header and menu with a scrolling content area. But that can be achieved much easier with CSS today. Furthermore frames allowed you to use common elements like logos and menus on multiple pages without using any server-side coding. This was an advantage at a time where server-side coding was tedious and error prone (i.e. CGI scripts), and many hosts didn't allow server-side scripting at all. Today with Content Management Systems (CMS) and better server-side platforms, this is much better handled on the server side.

So basically there are no advantages to using a frameset, just lots of problems.

IFrames can be used the same way that framesets were used, and in that case they also lead to the same problems. But there are also many legitimate uses of iframes which do not lead to the same problems.

ContentLicense: CC BY-SA 4.0