答:
A good approach could be using linked list. It is easy to keep the order, you can add or remove any item (creature) in any place in the linked list.

A demo:

```<code>              Last attacked
                |
c1 --> c2  --> c3 --> c4 --> c5 -
 ^                              |
 |------------------------------
</code>```

Player hits c3 and killed it

```<code>c1 --> c2  --x c3 --x c4 --> c5
^                      ^     |
|       | -------------|     |
|----------------------------
</code>```

Check how is next() after c3

```<code>           Current turn
               |
c1 --> c2 --> c4 --> c5
 ^                    |
 |--------------------|
</code>```

You can also keep extra data in the nodes beyond the link data. You can just follow the next() link to get the next node. Remove or add node any time you want.

Title: Should it use counter, or flag inside objects, to indicate progress?

Body:
For example, I have a game, it has 5 enemies which attack once sequentially at each round:

```<code>class Enemy{
};

class Game{
public:
    Enemy enemys[5];
};
</code>```

I want something to indicate which enemy has attacked and which has not, now I have 2 solutions:

1.add a counter "enemyIndex" to indicate which enemy is attacking, after each enemy attacked, the "enemyIndex" counter automatically +1:

```<code>class Enemy{
};

class Game{
public:
    int enemyIndex;
    Enemy enemys[5];
};
</code>```

2.each Enemy object adds a flag "isAttacked", after the enemy attacked, its  "isAttacked" flag marked from false to true:

```<code>class Enemy{
public:
    bool isAttacked;
};

class Game{
public:
    Enemy enemys[5];
};
</code>```

which one is more reasonable in terms of design pattern?

Body:
A good approach could be using linked list. It is easy to keep the order, you can add or remove any item (creature) in any place in the linked list.

A demo:

              Last attacked
                |
c1 --> c2  --> c3 --> c4 --> c5 -
 ^                              |
 |------------------------------

Player hits c3 and killed it

c1 --> c2  --x c3 --x c4 --> c5
^                      ^     |
|       | -------------|     |
|----------------------------

Check how is next() after c3

           Current turn
               |
c1 --> c2 --> c4 --> c5
 ^                    |
 |--------------------|

You can also keep extra data in the nodes beyond the link data. You can just follow the next() link to get the next node. Remove or add node any time you want.


问:
UUID vs Integer
For a database. Should I use an UUID or an integer for the primary key?

I will never exceed 2^32 in amount of rows, so an integer should be more than plenty.

I would prefer to use an integer, as I find it easier to work with, especially when using different languages.

Question: What is the advantage of UUIDs over integers?

答:
In addition to what Kilian Foth said, an advantage to UUIDs can be that they increase the address space and may be harder to guess.

Example: If you expose a REST API that contains the id of an entity in the path, a hacker might guess that if

GET http://mysupersensitive.data/supersecret/42 works,

GET http://mysupersensitive.data/supersecret/41 might work as well.

When it is UUIDs, this becomes much harder.

EDIT: The comment by Jules is right of course, this in itself must not be regarded as a security mechanism.

ContentLicense: CC BY-SA 3.0

Title: UUID vs Integer


问:
Should it use counter, or flag inside objects, to indicate progress?
For example, I have a game, it has 5 enemies which attack once sequentially at each round:

```<code>class Enemy{
};

class Game{
public:
    Enemy enemys[5];
};
</code>```

I want something to indicate which enemy has attacked and which has not, now I have 2 solutions:

1.add a counter "enemyIndex" to indicate which enemy is attacking, after each enemy attacked, the "enemyIndex" counter automatically +1:

```<code>class Enemy{
};

class Game{
public:
    int enemyIndex;
    Enemy enemys[5];
};
</code>```

2.each Enemy object adds a flag "isAttacked", after the enemy attacked, its  "isAttacked" flag marked from false to true:

```<code>class Enemy{
public:
    bool isAttacked;
};

class Game{
public:
    Enemy enemys[5];
};
</code>```

which one is more reasonable in terms of design pattern?

答:
You're confusing Enemy class, focus of performing anything and everything related to that particular enemy with its representation in the Game class.

The Enemy class should know what it means to attack, but it should not care about effects in other classes if it is not a direct effect of the attack.  In other words, an Enemy might need to perform some operation on its target, but it wouldn't need to retain state information related to whether or not it has attacked already.

The caller should know this and should keep track of this, and I assume the caller is the Game class itself.  If that is the case, then the solution is simple.  Your Game class should hold two lists:  one with a list of enemies which have not attacked and another with a list of enemies which have.  Create a private method in your Game class that performs the "attack" call for a particular enemy.  After the call, you remove it from the list of enemies that have not attacked and you add it to the list of enemies that have attacked.

Operations performed on all enemies would simply require two passes, one for each list.

If Game class doesn't call attack of Enemy, then Enemy will have to require a simple event handling system that allows other objects to listen.  Game will then subscribe to the attack event of all its enemy instances.  When an attack occurs, it will keep track of which enemies have attacked and which have not using the list system mentioned above.

Consider using the event bus pattern to centralize all events in your program if you feel the need to use many events like this.  Have an instance which allows a caller to listen or trigger an event by name.  Then you create a name "enemy.attacked" to indicate an event specific to an enemy attacking.  Similarly you can do the same for other events.

I hope this helps!


答:
Use a GUID/UUID

Honestly the number of times I heard "we will never run out of integers" only for whatever system to quickly run out of integers.

UUIDs offer significant advantages when you come to archiving data, replication and having code able to generate new Ids without writing to the database

Title: UUID vs Integer

Body:
For a database. Should I use an UUID or an integer for the primary key?

I will never exceed 2^32 in amount of rows, so an integer should be more than plenty.

I would prefer to use an integer, as I find it easier to work with, especially when using different languages.

Question: What is the advantage of UUIDs over integers?


问:
Motivating yourself to actually write the code after you've designed something
Does it happen only to me or is this familiar to you too?

It's like this: You have to create something; a module, a feature, an entire application... whatever. It is something interesting that you have never done before, it is challenging.

So you start to think how you are going to do it. You draw some sketches. You write some prototypes to test your ideas. You are putting different pieces together to get the complete view.

You finally end up with a design that you like, something that is simple, clear to everybody, easy maintainable... you name it. You covered every base, you thought of everything. You know that you are going to have this class and that file and that database schema. Configure this here, adapt this other thingy there etc.

But now, after everything is settled, you have to sit down and actually write the code for it. And is not challenging anymore.... Been there, done that! Writing the code now is just "formalities" and makes it look like re-iterating what you've just finished.

At my previous job I sometimes got away with it because someone else did the coding based on my specifications, but at my new gig I'm in charge of the entire process so I have to do this too ('cause I get payed to do it).

But I have a pet project I'm working on at home, after work and there is just me and no one is paying me to do it. I do the creative work and then when time comes to write it down I just don't feel like it (lets browse the web a little, see what's new on P.SE, on SO etc).

I just want to move to the next challenging thing, and then to the next, and the next...

Does this happen to you too? How do you deal with it?

How do you convince yourself to go in and write the freaking code?

I'll take any answer.

答:
I have always found that the original assumptions did not hold entirely and more or less of the original design had to be changed based on experience gathered while doing the actual implementation.

If you consider your design to be absolutely infallible and perfect after drawing some boxes, but before actually trying it out, I would consider you a perfect candidate for some project implementations.

Shipping is a feature.  If you don't go the whole distance, you are just an architect.

ContentLicense: CC BY-SA 2.5


问:
Should exceptions be raised higher up or lower down or both?
When calling some function in a Python application, the function often calls functions deeper down which again call functions deeper down, etc. It is easy to unknowlingly pass a bad value to the top-level function which will cause a failure further down. Naturally, the parameters should be checked and exceptions raised with helpful error messages. But where should this ideally be done, and why?

As high up as possible (error messages are probably easier to understand since they're closer to the user)

As low down as possible (exception messages are closer to where the errors would actually occur, and the checks may be simpler since they probably don't depend on some obscure combination of input values, but the messages and variable names might be so far removed from the user that the only way of knowing what actually must be changed in the top-level call is to inspect the source from top to bottom)

Both

答:
Python has 2 coding styles:

Easier to ask for forgiveness than permission (EAFP): This coding style is based on head leap and try. So you use a lot of try-except blocks instead of if statements

```<code>try:
    ham = spam.eggs
except AttributeError:
    handle_error()
</code>```

Look before you leap (LBYL): This method is preferred in languages like C and Java.

```<code>if hasattr(spam, 'eggs'):
    ham = spam.eggs
else:
    handle_error()
</code>```

That is not the Pythonic way for some developers and the docs explains some key points:

In a multi-threaded environment, the LBYL approach can risk introducing a race condition between “the looking” and “the leaping”. For example, the code, if key in mapping: return mapping[key] can fail if another thread removes key from mapping after the test, but before the lookup. This issue can be solved with locks or by using the EAFP approach.

Java language is the contrast of Python in this manner

(In Java) The moral of this story is simple:exceptions are, as their name impllies, to be used only for exceptional conditions; they should never be used for ordinary control flow.

This answer has a good demonstration on when to use EAFP and when not.

If you are using python, it is normal to use exception instead of if-conditions and handle the situation according to the exception you catch. That will make you use exception on every level of the code. So that leads you to the answer 3, or the option 4) any level that you can use. If execution time is very important, than you can check above SO question.

Body:
Python has 2 coding styles:

Easier to ask for forgiveness than permission (EAFP): This coding style is based on head leap and try. So you use a lot of try-except blocks instead of if statements

try:
    ham = spam.eggs
except AttributeError:
    handle_error()

Look before you leap (LBYL): This method is preferred in languages like C and Java.

if hasattr(spam, 'eggs'):
    ham = spam.eggs
else:
    handle_error()

That is not the Pythonic way for some developers and the docs explains some key points:

In a multi-threaded environment, the LBYL approach can risk introducing a race condition between “the looking” and “the leaping”. For example, the code, if key in mapping: return mapping[key] can fail if another thread removes key from mapping after the test, but before the lookup. This issue can be solved with locks or by using the EAFP approach.

Java language is the contrast of Python in this manner

(In Java) The moral of this story is simple:exceptions are, as their name impllies, to be used only for exceptional conditions; they should never be used for ordinary control flow.

This answer has a good demonstration on when to use EAFP and when not.

If you are using python, it is normal to use exception instead of if-conditions and handle the situation according to the exception you catch. That will make you use exception on every level of the code. So that leads you to the answer 3, or the option 4) any level that you can use. If execution time is very important, than you can check above SO question.


问:
multiplication with insufficiently long registers
I want to multiply two numbers but since I don’t have long enough registers in the current architecture need to “break them down” into shorter ones and somehow perform the calculation.

For example:

2048.125 x 2048.125 (2048.125 =>4001hex) but with the binary point beyond the 4th bit position (Q12.4 signed) and upwards .

Is there any way to split up the operation, and combine the results in the end?

Unfortunately the configuration am working on does not support well known libraries thus,I have to build one by myself.

Please provide any pointers that could lead to mathematical oriented implementation.Something that could possibly emerge out of manipulation of the partial products or similar.

Thanks

答:
I would try to avoid coding in assembler, and if possible adapt an existing C compiler to your target processor.

With GCC you have a lot of targets which could inspire you for your processor, and there are lots of documentation for that (see references in http://gcc-melt.org/docum.melt for more). Indeed it requires some effort (months of work).

Wide (but fixed size, e.g. two native ints -wide, such as 64 bits arithmetic on processors with 32 bits-wide words) arithmetic is done in GCC inside its libgcc/ directory, and most of that is coded in C (but depends a lot on how your GCC is configured and targeted). Even if you don't use or port GCC to your architecture (and I believe you really should), that libgcc should be inspirational (and IIRC, some books by Knuth explain the underlying algorithms, most of them being fairly intuitive.). Read also wikipage on fixed-point arithmetic.

If you want arbitrarily large integers, you need a bignum library. Don't reinvent your own (there are many tricky algorithms more efficient than the naive way you have learned at school, and you'll find several books and many research articles and conferences on the subject; you still can get a PhD on bignums and spend a full work life on them). Use an existing one, e.g. GMPlib.

Even for your own target processor, you should not code much in assembler. You'll better port some existing C compiler to it (and practically you need one, if you want your processor to be used).


问:
Never using Models, only ViewModels
I'm starting a new MVC 5 project from scratch. I'm using EF 6 (Database First) and Identity 2.0.

My solution consists of 3 different projects: Data (where I have a .edmx and my DB context), Resources (for localization purposes) and Web (the web project itself).

I'm using ViewModels for all my views, by default. Every time I create a new view, the first thing I do is add the ViewModel (if the ViewModels are connected between them, I keep them all in the same file; for example, all the ViewModels related to user accounts I keep in AccountViewModels). So far, this has made things very simple and solved several issues I was having before.

But I'm wondering, does it make sense for me to use Models at all? The only one I am using right now is the one for Identity, which is created by default and contains the ApplicationUser and ApplicationDbContext, both specific and necessary to Identity. Outside of that, it's everything ViewModels.

Would my Data project be considered the "Model" for my application? Thus, I am in fact using a Model, just that instead of being a bunch of classes I keep in Web\Models, it's a separate project where the "Models" (BL objects created by Entity) are stored. I think so, but I am not sure.

Is this a right approach, or could there be potential issues down the road? It's my first take on web programming so I would appreciate any advice.

答:
Would my Data project be considered the "Model" for my application?

Yes, that's exactly what Model is supposed to be.

Is this a right approach

I believe it is.

or could there be potential issues down the road?

There definitely will be. But description of your architecture is so vague, that we can only guess what kind of problems will you encounter.

Title: Never using Models, only ViewModels


问:
How might a Windows 8 Metro app handle back end database access?
While researching Metro and WinRT I haven't been able to find anything regarding enterprise apps and database access. All I hear about is the front end development.

Does anyone have any idea of how a Metro app will access a database server? Will this still be done through ASP.Net and ADO.Net? If not, then does anyone have any idea or guess as to how?

答:
Just in case you're interested, you can resort to MySQL instead of SQL Server. The MySQL Connector/Net has a WinRT component (DLL) you can reference from your WinRT/UAP Application in order to access a MySQL database. Syntax is similar to "regular" ADO.Net and it's really easy to use.

In case you hold the database in your same machine, you have to enable "localhost" access to WinRT/Metro apps using the CheckNetIsolation cmdlet, as explained here:

https://msdn.microsoft.com/en-US/library/windows/apps/hh780593.aspx

I don't know why Microsoft tries to complicate WinRT development so much, maybe they just don't want LOB applications using WinRT paradigm, but at least with databases we still have an alternative to SQLite to use "real" databases...


问:
What features would you like to have in PHP?
Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:

Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")

Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")

Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")

Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")

Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.

答: I really would like to have annotations.. afaik that RFC has been dropped.</p>


问:
Instance methods that modify multiple objects
I'm currently in the process of rewriting an older library for managing documents.

I'm having difficulties to specify an interface for the management of links between those documents. Previously they have been specified simply as the primary keys of the other documents. But in order to have a more object-oriented interface the primary keys should be replace with objects of the actual documents.

Now the implementation of the AddLink/RemoveLink methods are a problem because if you add a link from document A to document B another link from B to A is automatically added.

A more general description of the problem would be: How can you change properties that depend on each other but are in different objects (possibly behind interfaces).

Things I've tried so far:

Using internal methods to change the links "behind the back" of the object

This only works for normal classes but when interfaces are involved (my case) it won't work.

Using some kind of recursion detection mechanism, to simply stop at that point

This works but it's a hack in my opinion

Using event handlers (doesn't work for adding, only for removing)

Giving up on the idea of having direct access to the objects and just continue to use the primary keys

Example Code:

class Document
{
    private List<Document> links;

    public IReadOnlyList<Document> Links { get { return links.AsReadOnly(); } }

    public void AddLink(Document other)
    {
        links.Add(other);
        // How to add this to other.Links?
        // Just calling other.AddLink(this) would cause infinite recursion
    }
}
```

答:
OK, I don't see the advantage of having the object rather than the id, but..

one way to do this is to inject a Document/Link repository. so when you add the link, it gets added (as a two way link) to the repository. Both documents generate their links when queried by checking the (shared) repository.

ie.

```<code>    /// <summary>
    /// inject into documents, this access a shared database or its a shared instance etc
    /// </summary>
    public interface IRepository
    {
        Document GetDocument(string id);

        /// <summary>
        /// get all the links which are linked to or from the Id
        /// </summary>
        /// <param name="documentId"></param>
        List<Document> GetLinks(string documentId);

        /// <summary>
        /// add link refernce both docs
        /// </summary>
        /// <param name="linkFromId"></param>
        /// <param name="linkToId"></param>
        void AddLink(string linkFromId, string linkToId);
    }

    public class Document
    {
        public string Id {get;set;}

        private IRepository repo;

        public Document(IRepository repo)
        {
            this.repo = repo;
        }

        public IReadOnlyList<Document> Links
        {
            get
            {
                return repo.GetLinks(this.Id).AsReadOnly();
            }
        }

        public void AddLink(Document other)
        {
            repo.AddLink(this.Id,other.Id);
        }
    }
</code>```

Body:
OK, I don't see the advantage of having the object rather than the id, but..

one way to do this is to inject a Document/Link repository. so when you add the link, it gets added (as a two way link) to the repository. Both documents generate their links when queried by checking the (shared) repository.

ie.

    /// <summary>
    /// inject into documents, this access a shared database or its a shared instance etc
    /// </summary>
    public interface IRepository
    {
        Document GetDocument(string id);

        /// <summary>
        /// get all the links which are linked to or from the Id
        /// </summary>
        /// <param name="documentId"></param>
        List<Document> GetLinks(string documentId);

        /// <summary>
        /// add link refernce both docs
        /// </summary>
        /// <param name="linkFromId"></param>
        /// <param name="linkToId"></param>
        void AddLink(string linkFromId, string linkToId);
    }

    public class Document
    {
        public string Id {get;set;}

        private IRepository repo;

        public Document(IRepository repo)
        {
            this.repo = repo;
        }

        public IReadOnlyList<Document> Links
        {
            get
            {
                return repo.GetLinks(this.Id).AsReadOnly();
            }
        }

        public void AddLink(Document other)
        {
            repo.AddLink(this.Id,other.Id);
        }
    }


答:
Short answer is "Both".

You might want to trap "errors" early on, throwing out bad data (although whether that's an "Exception" is debatable). You definitely want to throw exception when things go "badly wrong", and that tends to be lower down in the layers of code.

A question to consider before throwing an Exception - "Then what?"
If your code throws an exception, what is someone else's code going to do about it?

This is why there are lots of Exception classes, rather than just an "Error" object that happens to have some [arbitrary] error "Number" associated with it.

If a piece of code can catch your exception, analyse what went wrong (perhaps from what's passed in the Exception) and then recover from that the situation, all without the User knowing anything happened at all, then you're on to a Winner.  Use specific Exception classes that can be caught and handled separately.

If all you ever want to do is dump the exception into a log file (never show the whole thing on screen!) then re-using the supplied, basic Exception classes is probably all you'll ever need.

Title: Should exceptions be raised higher up or lower down or both?

Body:
When calling some function in a Python application, the function often calls functions deeper down which again call functions deeper down, etc. It is easy to unknowlingly pass a bad value to the top-level function which will cause a failure further down. Naturally, the parameters should be checked and exceptions raised with helpful error messages. But where should this ideally be done, and why?

As high up as possible (error messages are probably easier to understand since they're closer to the user)

As low down as possible (exception messages are closer to where the errors would actually occur, and the checks may be simpler since they probably don't depend on some obscure combination of input values, but the messages and variable names might be so far removed from the user that the only way of knowing what actually must be changed in the top-level call is to inspect the source from top to bottom)

Both


问:
Service Layer to Retrieve Data Specific to Views
I'm building a WPF application, using MVVM, and Prism. It's worth noting that I'm the only developer working on a large project, so resources are limited. Here's what I currently have:

Models - POCO's

ViewModels - contain instances of POCO's, and utilizes the service layer based on user interaction.

Views - bound to ViewModels

Services - WCF services for persistence, data retrieval

I'm using Dapper to map query results to my models.

I'm curious as to how others, that don't use an ORM, handle data retrieval given that myriad of variations if returning the fully loaded POCO object would cause a pretty significant query execution.

E.G.

```<code>public class Customer : BindableBase
{
   public string Name{ get; set; }
   public ObservableCollection<Address> Addresses { get; set; }
   public ObservableCollection<Contact> Contacts { get; set; }
}

public class Contact : BindableBase
{
   public ObservableCollection<PhoneNumber> PhoneNumbers { get; set; }
}
</code>```

When looking at search results for Customers, we may only display Name. So a query like SELECT Name FROM dbo.Customer would suffice.

When editing a customer record, we need most of the data retrieved related to the Customer record, so there would be joins in the query to grab the addresses, contacts, and phone numbers.

... and there are umpteen other options, maybe they only need addresses, or just contacts.

The service layer will be used in other applications and technologies, and as such I'm going to have my business logic in there as a centralized location. Am I going to be stuck creating a function in the service layer to handle each scenario?  E.G.  GetSearchData(string searchCriteria) ... GetCustomerWithAddresses(int customerId) ...   if so how would you go about structuring the project? I've read somewhere that another person has the service layer return the view model, which I'm not necessarily a fan of. I would still need the generic functions that return basic data for other technologies that consume the services.

答:
Usually with a Customer object I would fully populate it. Although you want the possibility of multiple addresses etc you normally have only one or two and you tend to be dealing with a single customer at a time.

However, if you start having many sub objects or are dealing with many customers at a time (say for a report) I would remove all the sub objects (I usually use poco to mean only simple objects) and expose the relationships via the repository.

ie

```<code>repo.GetAddressesForCustomer(customerId)

class Address
{
    string CustomerId {get;set;}
    ...
}
</code>```

This allows you to, limit your returned data to only that which is needed and also to optimise your queries for the specific dataset you want to retrieve.

Say for example we want to show a list of customers with active orders, showing  id, name and postcode of primary address.

Loading the full object one by one would entail n+1 db queries, even if we lazy load via EF or some other clever ORM we could end up with an inefficient query with wierd joins. But if we retain control at the repository layer we can populate our view model with

```<code>repo.GetCustomersWithActiveOrders();
repo.GetPrimaryAddressesOfCustomersWithActiveOrders();
</code>```

Body:
Usually with a Customer object I would fully populate it. Although you want the possibility of multiple addresses etc you normally have only one or two and you tend to be dealing with a single customer at a time.

However, if you start having many sub objects or are dealing with many customers at a time (say for a report) I would remove all the sub objects (I usually use poco to mean only simple objects) and expose the relationships via the repository.

ie

repo.GetAddressesForCustomer(customerId)

class Address
{
    string CustomerId {get;set;}
    ...
}

This allows you to, limit your returned data to only that which is needed and also to optimise your queries for the specific dataset you want to retrieve.

Say for example we want to show a list of customers with active orders, showing  id, name and postcode of primary address.

Loading the full object one by one would entail n+1 db queries, even if we lazy load via EF or some other clever ORM we could end up with an inefficient query with wierd joins. But if we retain control at the repository layer we can populate our view model with

repo.GetCustomersWithActiveOrders();
repo.GetPrimaryAddressesOfCustomersWithActiveOrders();


问:
Classes with one public function replaced with a constructor
I have a number of classes with a single public method. Looking at this answer, I tend to agree with what is stated.

The OP lists some examples, which I interpret to be used like

```<code>(new VideoCompressor)->compress($raw_video);
</code>```

While the readability improves slightly by calling the explicit method name, I feel it is almost as readable by simply moving the parameters to a __construct() and calling the compress function from within the constructor.

```<code>new VideoCompressor($raw_video);
</code>```

This however would add a constructor to the class if it didn't have one already.

In my eyes it would be a trade between slightly smaller calls to classes in exchange for more code within the class.

Is there any other reason either method should be preferred other than personal taste?

答:
Calling the compress function is the correct approach. That way you can easily implement multiple compression methods.

```<code>interface VideoCompression
{
    public function compress($rawVideo);
}

final class MP4VideoCompression implements VideoCompression
{
    public function compress($rawVideo) { }
}

final class H264VideoCompression implements VideoCompression
{
    public function compress($rawVideo) { }
}
</code>```

Then later in your app you can get the video compression class based on user's input via a factory, for example.

Update: After checking the original thread I realized MainMa posted exactly the same approach as me with further reasons why to use that way.

Body:
Calling the compress function is the correct approach. That way you can easily implement multiple compression methods.

interface VideoCompression
{
    public function compress($rawVideo);
}

final class MP4VideoCompression implements VideoCompression
{
    public function compress($rawVideo) { }
}

final class H264VideoCompression implements VideoCompression
{
    public function compress($rawVideo) { }
}

Then later in your app you can get the video compression class based on user's input via a factory, for example.

Update: After checking the original thread I realized MainMa posted exactly the same approach as me with further reasons why to use that way.


答:
Would this work?  Yes.  Is this proper class design? No.

A constructor's purpose is to ensure valid creation (construction) of the instance, no more and no less.

Title: Classes with one public function replaced with a constructor

Body:
I have a number of classes with a single public method. Looking at this answer, I tend to agree with what is stated.

The OP lists some examples, which I interpret to be used like

```<code>(new VideoCompressor)->compress($raw_video);
</code>```

While the readability improves slightly by calling the explicit method name, I feel it is almost as readable by simply moving the parameters to a __construct() and calling the compress function from within the constructor.

```<code>new VideoCompressor($raw_video);
</code>```

This however would add a constructor to the class if it didn't have one already.

In my eyes it would be a trade between slightly smaller calls to classes in exchange for more code within the class.

Is there any other reason either method should be preferred other than personal taste?


问:
How is an interface used in Dependency Injection?
I'm working on a simple DI library, and on the subject of using services through interfaces, I can't find the usefulness. Perhaps it's because I dont fully or properly understand how an interface should be used during the process of injecting dependencies.

Here's what I (think I) understand:

DI consists primarily of clients and services. Interfaces allow the injector to tell the client which variables and methods are available through a specific service.

If that isn't wrong:

It seems to me that the interface could pass available property names and what type they are, so my client can know if they're functions or values, but that doesn't seem useful since I can do that with or without the interface. Whether the methods/values are utilized via an interface or via the injected service, I can know their types because I can use the typeof operand (JavaScript) regardless to check the type of the property I'm about to use.

So I think that I must not have a proper understanding of what interfaces should do. How are interfaces used in dependency injection?

答: The benefit isn't that the interface declares the members and methods that a client needs--which is exactly what a concrete class can do. The benefit is that a concrete class can implement an interface, which allows you to swap out the dependency at run-time. For testing, you may want to pass in a mock implementing the same interface, but without all the overhead of the usual class (database calls, perhaps). Your class only depends on an interface, but the implementation is left for the DI/IoC container to inject.


答:
As a quick example. I hope you see that tieing the consturction of an object to the moment of use eliminates dependancy injection, ties you to a concrete type eliminating polymorphism (using a different IVideoCompressor is now impossible) and is generally bad:</p>

```<code>    interface IVideoCompressor
    {
        Compress();
    }

    class VideoCompressor : IVideoCompressor
    {
        public byte[] Compress(byte[] input){
             throw new NotImplementedException();
        }
    }

    public class DirectoryFiddler
    {
        IVideoCompressor _videoComp;

        public DirectoryFiddler(IVideoCompressor videoComp, IImageCompressor imageCOmp)
        {
            _videoComp = videoComp;
        }

        public byte[] DoSomething(Idirectory directory)
        {
            // DI, polymorphism, in general good stuff
            return _videoComp.Compress(directory.Video);
        }

        public byte[] DoSomething2(Idirectory directory)
        {
            // Tied to VideoCompressor
            return new VideoCompressor(directory.Video).Compress();
        }
    }
</code>```

Body:
As a quick example. I hope you see that tieing the consturction of an object to the moment of use eliminates dependancy injection, ties you to a concrete type eliminating polymorphism (using a different IVideoCompressor is now impossible) and is generally bad:

    interface IVideoCompressor
    {
        Compress();
    }

    class VideoCompressor : IVideoCompressor
    {
        public byte[] Compress(byte[] input){
             throw new NotImplementedException();
        }
    }

    public class DirectoryFiddler
    {
        IVideoCompressor _videoComp;

        public DirectoryFiddler(IVideoCompressor videoComp, IImageCompressor imageCOmp)
        {
            _videoComp = videoComp;
        }

        public byte[] DoSomething(Idirectory directory)
        {
            // DI, polymorphism, in general good stuff
            return _videoComp.Compress(directory.Video);
        }

        public byte[] DoSomething2(Idirectory directory)
        {
            // Tied to VideoCompressor
            return new VideoCompressor(directory.Video).Compress();
        }
    }


答:
There are at least three reasons you might want to inject an interface instead of a concrete class:

You have multiple implementations of that interface, and want the container to select one at run-time.

You want to write unit tests that isolate out the injected service, and so want to provide a mock implementation for the test (this is arguably the same as #1, since a mock is just another implementation, even if it's provided by a mock framework).

You have some form of Onion Architecture, where your consuming class is in an assembly does not have knowledge of the implementation's assembly, but does have knowledge of a common assembly (where the interface would reside).

It is otherwise perfectly acceptable to inject concrete types.  I actually asked about injecting concrete types on SO here.

Title: How is an interface used in Dependency Injection?

Body:
I'm working on a simple DI library, and on the subject of using services through interfaces, I can't find the usefulness. Perhaps it's because I dont fully or properly understand how an interface should be used during the process of injecting dependencies.

Here's what I (think I) understand:

DI consists primarily of clients and services. Interfaces allow the injector to tell the client which variables and methods are available through a specific service.

If that isn't wrong:

It seems to me that the interface could pass available property names and what type they are, so my client can know if they're functions or values, but that doesn't seem useful since I can do that with or without the interface. Whether the methods/values are utilized via an interface or via the injected service, I can know their types because I can use the typeof operand (JavaScript) regardless to check the type of the property I'm about to use.

So I think that I must not have a proper understanding of what interfaces should do. How are interfaces used in dependency injection?


问:
How do I store multiple views of data in memory?
I have a bunch of modules. I can break these modules into different categories that are complete and do not overlap. For example, three categories, with ids that can be expressed as Animal, Vegetable, and Mineral. I further break these categories down into subcategories, which again are distinct, complete and do not overlap. For example, ids that can be expressed as Mammal, Reptile, Legume, Root, Rock, Gem. Finally, underneath these categories, there are the modules themselves, e.g. Cat, Dog, Iguana, Bean, Quartz, Emerald, etc.

Here are my common use cases:

I need to call various methods on all modules.

I need to get flat snapshot of the current state of all data across all modules.

I need to call various methods on all modules in a particular category (but not subcategory).

I need to call various methods on a particular specific module based on it's known ID.

This could be a "do something" or a "tell me some data about yourself"

I need to store aggregate data about all modules in a particular category (but not subcategory).

How should I store this data?

Some other relevant facts:

The categories are established in runtime

As such, the bottom level modules do share a common interface.

Once they're set up, they don't change in that particular run - they are based on data in configuration files.

Here's what I currently do:

I have a class that contains a Map<Category, CategoryDataStructure>. This class also maintains a separate Collection<Module> view of the data for use with requirement #2.

CategoryDataStructure has chained delegation methods that send the method call down the chain, via SubCategoryDataStructure.

CategoryDataStructure also stores the aggregate data used in requirement #5.

It works, but it's honestly quite unwieldy. The whole thing is stateful / mutable and hard to change. If I want to add new behavior I have to add it in many places. Currently the data structures themselves have a lot of business logic as well; the delegation methods. Also the parent data structure has to do a lot of business logic to create a particular module and it's parent data structure if need and that parent's data structure if needed.

I'm looking to somehow break apart data management logic away from the data structure itself, but because of the nesting it's complicated. Here are some other options I've been considering:

Create a simple Map<Category, Map<Subcategory, Module>>, and put all the code to keep its state in a different class. My concern with doing this is requirements #1 and #2, it will be difficult to keep the view consistent as now I'll have two different data structures that represent the same data.

Do everything in a flat data structure, and loop through the entire structure when I'm looking for a particular category or sub category.

答:
It appears that the core issue here is you have objects arranged in a hierarchy based on their identity, but are using them in a non-hierarchical manner.

An analogy would be storing files in directories based on their file type, but searching through each directory and only loading certain ones based on some criteria other than the type.

I'm looking to somehow break apart data management logic away from the
  data structure itself, but because of the nesting it's complicated.
  Here are some other options I've been considering:

This is a good goal, and there is an easy way to start splitting the responsibilities without a major refactor: use Visitors.

The idea is that if you need to inspect or operate on only certain elements in the hierarchy, you put that logic in the visitor itself. You can then write multiple visitors, each one operating on different elements, and performing different actions.

Each unit of logic is now self-contained to a specific visitor. This enhances the SRP-ness of your code. If you need to change how an operation is done, you do so only in the visitor that implements that logic. Your object hierarchy should stay the same, minus superficial changes to expose necessary data.

There are multiple ways to implement visitors depending on the specific goals, but the general idea is each node in the hierarchy accepts a visitor object. Its implementation looks like this, and can be stuffed into some abstract parent class:

```<code>public class Node {
  public void accept(Visitor v) {
    v.accept(this);
    for (Node child : children) {
      child.accept(v);
    }
  }
}
</code>```

This ensures that no matter how you wire up your nodes at runtime, every node will be processed.

Your visitor looks like this:

```<code>public interface Visitor {
  accept(Node n);
}
</code>```

The visitor's accept(Node) method is where the real work is done. You will need to inspect the node and conditionally do different things (including ignore the node).

For example, you might be able to do the following:

```<code>Node root = ...;

// Print information on the hierarchy.
root.accept(new DebugVisitor());

// Does stuff with modules, ignores subcategories.
root.accept(new FrobnicateModulesVisitor());

// Eats vegetables, ignores animals and minerals.
root.accept(new EatYourVegetableVisitor());
</code>```

Each visitor is a self-contained class that contains the logic for each operation with no need to mix concerns with other visitors or the nodes.

Body:
It appears that the core issue here is you have objects arranged in a hierarchy based on their identity, but are using them in a non-hierarchical manner.

An analogy would be storing files in directories based on their file type, but searching through each directory and only loading certain ones based on some criteria other than the type.

I'm looking to somehow break apart data management logic away from the
  data structure itself, but because of the nesting it's complicated.
  Here are some other options I've been considering:

This is a good goal, and there is an easy way to start splitting the responsibilities without a major refactor: use Visitors.

The idea is that if you need to inspect or operate on only certain elements in the hierarchy, you put that logic in the visitor itself. You can then write multiple visitors, each one operating on different elements, and performing different actions.

Each unit of logic is now self-contained to a specific visitor. This enhances the SRP-ness of your code. If you need to change how an operation is done, you do so only in the visitor that implements that logic. Your object hierarchy should stay the same, minus superficial changes to expose necessary data.

There are multiple ways to implement visitors depending on the specific goals, but the general idea is each node in the hierarchy accepts a visitor object. Its implementation looks like this, and can be stuffed into some abstract parent class:

public class Node {
  public void accept(Visitor v) {
    v.accept(this);
    for (Node child : children) {
      child.accept(v);
    }
  }
}

This ensures that no matter how you wire up your nodes at runtime, every node will be processed.

Your visitor looks like this:

public interface Visitor {
  accept(Node n);
}

The visitor's accept(Node) method is where the real work is done. You will need to inspect the node and conditionally do different things (including ignore the node).

For example, you might be able to do the following:

Node root = ...;

// Print information on the hierarchy.
root.accept(new DebugVisitor());

// Does stuff with modules, ignores subcategories.
root.accept(new FrobnicateModulesVisitor());

// Eats vegetables, ignores animals and minerals.
root.accept(new EatYourVegetableVisitor());

Each visitor is a self-contained class that contains the logic for each operation with no need to mix concerns with other visitors or the nodes.


答:
A deep level of nesting suggests that you should refactor actions into smaller functions, which can be chained using return statements. If you need to apply the same method for multiple inputs you could take advantage of function.apply() in Java 8.

Assuming that the different items do not share any properties, you could implement an interface, which requires that a specific set of methods are implemented. For each level I would create one interface, which is then extended for each sub-node, for example: Entity, Phylum, Species. In addition you need three classes for each of the three entities.

The data can be stored as properties of the object instances. To achieve a flat snapshot I would iterate across the data using function.apply().

Title: How do I store multiple views of data in memory?

Body:
I have a bunch of modules. I can break these modules into different categories that are complete and do not overlap. For example, three categories, with ids that can be expressed as Animal, Vegetable, and Mineral. I further break these categories down into subcategories, which again are distinct, complete and do not overlap. For example, ids that can be expressed as Mammal, Reptile, Legume, Root, Rock, Gem. Finally, underneath these categories, there are the modules themselves, e.g. Cat, Dog, Iguana, Bean, Quartz, Emerald, etc.

Here are my common use cases:

I need to call various methods on all modules.

I need to get flat snapshot of the current state of all data across all modules.

I need to call various methods on all modules in a particular category (but not subcategory).

I need to call various methods on a particular specific module based on it's known ID.

This could be a "do something" or a "tell me some data about yourself"

I need to store aggregate data about all modules in a particular category (but not subcategory).

How should I store this data?

Some other relevant facts:

The categories are established in runtime

As such, the bottom level modules do share a common interface.

Once they're set up, they don't change in that particular run - they are based on data in configuration files.

Here's what I currently do:

I have a class that contains a Map<Category, CategoryDataStructure>. This class also maintains a separate Collection<Module> view of the data for use with requirement #2.

CategoryDataStructure has chained delegation methods that send the method call down the chain, via SubCategoryDataStructure.

CategoryDataStructure also stores the aggregate data used in requirement #5.

It works, but it's honestly quite unwieldy. The whole thing is stateful / mutable and hard to change. If I want to add new behavior I have to add it in many places. Currently the data structures themselves have a lot of business logic as well; the delegation methods. Also the parent data structure has to do a lot of business logic to create a particular module and it's parent data structure if need and that parent's data structure if needed.

I'm looking to somehow break apart data management logic away from the data structure itself, but because of the nesting it's complicated. Here are some other options I've been considering:

Create a simple Map<Category, Map<Subcategory, Module>>, and put all the code to keep its state in a different class. My concern with doing this is requirements #1 and #2, it will be difficult to keep the view consistent as now I'll have two different data structures that represent the same data.

Do everything in a flat data structure, and loop through the entire structure when I'm looking for a particular category or sub category.


问:
OO design patterns similar to Drupal's hook system?
The core of the CMS Drupal is not based in object-orientation in version 7. For writing pluggable modules, it has a "hook" system, whereby you can alter the behavior (by altering passed data) for defined system functions.

For instance, Drupal ha and API through which you create arrays to define forms that are translated into HTML. There is a defined hook called hook_form_alter whereby you can alter any form array after its created, and before its rendered, allowing you to change the form entirely. Similarly, you can do the same for queries, emails, etc generated through the API.

I am not well-versed in OO or design patterns, so background and expoundings are helpful. Also, I'm coming out of only PHP (and MySQL), so I'm not familiar with examples of how other languages do things.

Since these are all based on functions and callbacks, I wonder what object-oriented design patterns give you this functionality.

答:
Isn't this the delegation pattern?

E.g. define an AlterFormProcessor interface for your hook delegate, add .setAlterFormProcessor(AlterFormProcessor hook) to your service. If the hook has been set, call it and collect the result.

For even more complex forms of processing, implement .addWhateverProcessor() instead of .setWhateverProcessor and run whole pipelines of delegated processors. Remember how event processing is done in AWT or in browser JavaScript.


答:
What you may be looking for is Aspect Oriented Programming, which is an extension of OO that adds a facility for performing hooks (called "pointcuts") at method invocations selected by a description of the calls to intercept.

Alternatively, the Decorator pattern is a pure OO way of achieving some of the same results, but does require more work to set up.

Title: OO design patterns similar to Drupal's hook system?

Body:
The core of the CMS Drupal is not based in object-orientation in version 7. For writing pluggable modules, it has a "hook" system, whereby you can alter the behavior (by altering passed data) for defined system functions.

For instance, Drupal ha and API through which you create arrays to define forms that are translated into HTML. There is a defined hook called hook_form_alter whereby you can alter any form array after its created, and before its rendered, allowing you to change the form entirely. Similarly, you can do the same for queries, emails, etc generated through the API.

I am not well-versed in OO or design patterns, so background and expoundings are helpful. Also, I'm coming out of only PHP (and MySQL), so I'm not familiar with examples of how other languages do things.

Since these are all based on functions and callbacks, I wonder what object-oriented design patterns give you this functionality.


问:
Algorithm to identify degree of similarity based on prior categorization
I am working with digital images that people have manually categorized on a number of parameters.

I want to be able to find images that are similar or dissimilar based on certain categories. For instance, we might want to pick two random images from our database that have similar "significance", but are otherwise as different as possible.

As an example, this picture of Stonehenge would be categorized like this:

```<code>colors: blue, green, grey
themes: natural, land, sky
brightness: light
location: outdoor
shapes: angular
texture: hard
lines: vertical
significance: historical
</code>```

The categories are mostly fixed and small, so when manually categorized the person is choosing the main colors from a list of ten colors (red, orange, yellow, green, blue, purplse, white, black, grey, brown), and the same is true of the other categories. Most of the categories only have a small number of options, such as location is indoor, outdoor, or unknown, and brightness is light, dark, or neutral.

My naive approach is something like this:

Query the database for pictures with historical significance

Pick a random starting image from the historically significant images

Of the remaining historical images, do a random sampling of N images. Different values of N will give us more variety at the expense of accuracy.

For each randomly selected image, create an ordered binary vector for all possible category values (ex. red=0, blue=1, outdoor=1, etc), producing some binary value.

Compare the binary values for the starting image and the random image, for example by using a bitwise XOR operation (or equivalent set operation), then count the number of 1's in the result.

I am not necessarily interested in finding the most dissimilar images. Any two images that are mostly dissimilar will be fine, and in fact we typically do want some randomness so the same images pairs are not frequently selected.

This naive approach works okay. Are there any proper algorithms or techniques I should look at that might apply to this problem?

答:
Everything you said sounds close, but it's missing some details on vector creation and querying that are important. Ideally you need to form unique vectors for each image. You'll need to convert the color into HSV (or HSL) or a color space that lends itself to comparisons. Assign a number to each choice for the components.

Next assign a weight to each component in your vector. This should normalize the importance of each component. If you can imagine your vector in n-dimensional space you want each component to have equal weight (or be biased by its importance in the comparison). As an example lines might not be important so in the range [0, 1] horizontal = 0.2 and vertical = 0.4. Outdoor might be an important distinction so indoor = 0.5 and outdoor = 1.0. (You don't have to stay between 0 and 1, but it does keep it simple).

For colors you have to handle them specially. For color assign each component a number between [0, 1] (for each HSV component).

My only worry with your setup is your categorization is very simple and your color and theme system is a bit complex having multiple colors and themes. When generating a vector you'd essentially want to union the results with the vector and each color and theme. So for a single image with you'd generate every combination of vector (filtering for components you're searching for). Example:

(blue, natural,light, ...)

(blue, land, light, ...)

(blue, sky, light, ...)

(green, natural, light, ...)

(green, land, light, ...)

(green, sky, light, ...)

(grey, natural, light, ...)

(grey, land, light, ...)

(grey, sky, light, ...)

You'd convert each component to their numeric weighted values, so you'd have a real vector in n-dimensional space. (blue would be converted to 3 HSV components just to be very clear).

When you have vectors based on the parameters you want to compare you'd normally use a k-d tree nearest neighbor look-up.

https://en.wikipedia.org/wiki/K-d_tree#Nearest_neighbour_search

Then perform for each vector an n neighbor look-up to get a set of vectors associated with an image. Then union the resulting sets. If you find nothing increase n in your sampling. You can use a dot product calculation averaged for all vector comparisons to kind of get a similarity factor if you're looking for a percentage of similarity. (Might need to be clever in that regard if you compare a lot of components since it'll make the images appear more dissimilar than they might seem to the eye).

This is a very rough overview of k-d tree data mining. You'd need to read a data mining book to get the more exact answer and other approaches. (Creating the weights though is a bit of an art since it's up to you if color is more important than theme or shape).


问:
How can I convince management to deal with technical debt?
This is a question that I often ask myself when working with developers. I've worked at four companies so far and I've become aware of a lack of attention to keeping code clean and dealing with technical debt that hinders future progress in a software app. For example, the first company I worked for had written a database from scratch rather than use something like MySQL and that created hell for the team when refactoring or extending the application. I've always tried to be honest and clear with my manager when he discusses projections, but management doesn't seem interested in fixing what's already there and it's horrible to see the impact it has on team morale.

What are your thoughts on the best way to tackle this problem?
What I've seen is people packing up and leaving. The company then becomes a revolving door with developers coming in and out and making the code worse. How do you communicate this to management to get them interested in sorting out technical debt?

答:
You need to give your management a financial reason to deal with technical debt, and a framework for managing reducing that technical debt.

Maintaining a technological roadmap is one such framework. Starting out with a roadmap will help you keep you from piling on technical debt, and can also help you reduce existing debt as well.

Many successful long-term projects have associated steering committees and roadmaps to guide development. These are especially helpful when there are multiple development teams and stakeholders involved.

My suggestion is that you discuss this strategy with your managers (and if possible those who make decisions on where money gets spent).

The general approach to creating and managing a roadmap are straightforward, but it does require the support of your management team. First, define a goal. Define the elements of the technical debt, and develop a target system architecture that reduces elements of your technical debt. Remember, it doesn't have to be perfect, just workable and better than what you currently are. Take into account software, development tools, hardware platforms, major new features that may be added to the system. Do a cost analysis. If you have the desired architecture, what are the tangible benefits of performing the refactoring? (Benefits would include reduced test time, more reliable software products, more predictable development cycles, etc.) If you can show enough benefits to performing refactoring, you can get management support.

Once you have a roadmap and management support, develop a series of steps (also called a plan) that you need to take to get to this desired state. It may be a good idea to put together a steering committee that maintains the roadmap, trains and educates the development teams on the roadmap, and periodically reviews changes for architectural integrity.

Roadmaps are really useful, and perhaps the 13th question on the Joel Test should be "Do you have a roadmap?"

Here is a video of the first hour of a recent Red Hat Linux roadmap session.


答:
Sirisian's answer started along the right path, but then he lost me, so here is my take on the issue.

The fact that you are dealing with images is irrelevant, and the fact that one of the properties must be identical is also irrelevant.  They are both red herrings.  All I see here is entities with properties, and the problem can easily be redefined to exclude the property which must be identical, and to only consider the subset of entities that do in fact have the same value on that excluded property.

So, basically, what you have is a set of entities where each entity has a list of N properties, and you have a separate entity which we will call the "reference" entity, and you want to search through that set to find entities that have as dissimilar as possible values from the reference entity.

Essentially, you want a maximum distance in N-dimensional space algorithm.

First of all you need to compute the N-dimensional vector of the values of your reference entity.  This is essentially the coordinates of a point in N-dimensional space. (If you want, you can imagine that N = 3, so you can be thinking of the problem in 3-dimensional space.)

Then, you need to loop through the rest of your entities, and for each entity you need to calculate its N-dimensional vector, (imagine another point in 3-dimensional space,) then you need to calculate the distance between the reference vector and this vector, which is going to be another N-vector, and then you need to take the absolute value, a.k.a. magnitude of that vector, which will be a single value, and store it.

Once all the magnitudes have been collected, you need to sort all your entities by this magnitude value, and your desired results will be gathered near the end of the list, where the largest magnitudes will be.

This is the standard way of solving the bulk of your problem, and I would strongly advise solving it precisely like that, so as to be implementing an algorithm which will be understandable by others, and also by yourself, should you revisit it a few months later.

Now, your particular situation has certain peculiarities:

The values of your properties are not nice real numbers, they are sets of discrete values. So, you will need to map them to real numbers.  A range from 0 to 1 will work just fine, as Sirisian suggested. You can probably combine your discrete color and your discrete brightness together into three property values, whether they be HSV, HSL, or perhaps even RGB, I don't think it will matter much.

You want a variable number of results, and you want some randomness.  So, select a percentage of entities at the end of the sorted list, and choose a specific number from them, at random.

Title: Algorithm to identify degree of similarity based on prior categorization

Body:
I am working with digital images that people have manually categorized on a number of parameters.

I want to be able to find images that are similar or dissimilar based on certain categories. For instance, we might want to pick two random images from our database that have similar "significance", but are otherwise as different as possible.

As an example, this picture of Stonehenge would be categorized like this:

```<code>colors: blue, green, grey
themes: natural, land, sky
brightness: light
location: outdoor
shapes: angular
texture: hard
lines: vertical
significance: historical
</code>```

The categories are mostly fixed and small, so when manually categorized the person is choosing the main colors from a list of ten colors (red, orange, yellow, green, blue, purplse, white, black, grey, brown), and the same is true of the other categories. Most of the categories only have a small number of options, such as location is indoor, outdoor, or unknown, and brightness is light, dark, or neutral.

My naive approach is something like this:

Query the database for pictures with historical significance

Pick a random starting image from the historically significant images

Of the remaining historical images, do a random sampling of N images. Different values of N will give us more variety at the expense of accuracy.

For each randomly selected image, create an ordered binary vector for all possible category values (ex. red=0, blue=1, outdoor=1, etc), producing some binary value.

Compare the binary values for the starting image and the random image, for example by using a bitwise XOR operation (or equivalent set operation), then count the number of 1's in the result.

I am not necessarily interested in finding the most dissimilar images. Any two images that are mostly dissimilar will be fine, and in fact we typically do want some randomness so the same images pairs are not frequently selected.

This naive approach works okay. Are there any proper algorithms or techniques I should look at that might apply to this problem?


问:
How important it is to fix memory leaks?
I found by Valgring that some GTK+ programs leaks memory. How important it is to fix those leaks? I mean, often those programs works very well but on the other hand, one can never be sure if one wants to copy part of the leaking code to some other program. And I'm not sure if the idea of GTK+-programs is to work fast and therefore there are leaks.

So if I sometimes find a memory leak in an open source program, should I fix it or are there for example efficiency issues and therefore programmers original idea was to write some small leaking code?

答:
How important it is to fix memory leaks depends on the severity of the problem and what else you have to do that is important. My experience is that small memory leaks tend to be rather benign for most applications. The lifetime of a desktop app session is not usually long enough to see any degradation from a small memory leak.

If you are writing a server that runs 24/7, then small memory leaks can add up over time and become a major problem. But that's why many companies schedule their servers to restart daily or weekly. The effort to find memory leaks is often excessive relative to what might be gained, so it's easier to restart the servers on a regular basis and move on to more important things.


答:
Dependency Injection is handing a piece of software its dependencies at runtime, instead of coding that piece of software in such a way that it has statically bound, hard-coded, intimate knowledge of the precise type and instance of each one of its dependencies.

For example, this is without DI:

```<code>function prepareToDrink()
{
     TheOneAndOnlyGloballyAvailableHeinekenBottle.open();
}
</code>```

And this is with DI:

```<code>function prepareToDrink( Bottle anyBottle )
{
     anyBottle.open(); //also works with that Budweisser bottle. Also with champagne.
}
</code>```

As you can see, not only will it work with any beer Bottle in the house, but also with other kinds of bottles, assuming that the other bottles are derived from the same basic Bottle class.

The definition you found chooses to call the "piece of software" a "client", and the dependency a "service", but elaborate talk of this kind can be misleading at times.

A dependency is really anything that your piece of software needs in order to do its job.  (It depends on it.)  It may be an object, or it may be an interface; but if it was to be an object, then that object would have to be of a specific class, or a class more derived from it, and this would be a bit limiting.  We prefer to use interfaces so that we can pass any class we like, without it having to be derived from a specific class.

So, for example, if we want to also be able to open beer cans, but Can is not derived from Bottle, we can have both Can and Bottle implement the Openable interface, in which case we can do this:

```<code>function prepareToDrink( Openable anythingThatSupportsOpening )
{
    anythingThatSupportsOpening.open(); //opens bottles; also opens cans.
}
</code>```

Body:
Dependency Injection is handing a piece of software its dependencies at runtime, instead of coding that piece of software in such a way that it has statically bound, hard-coded, intimate knowledge of the precise type and instance of each one of its dependencies.

For example, this is without DI:

function prepareToDrink()
{
     TheOneAndOnlyGloballyAvailableHeinekenBottle.open();
}

And this is with DI:

function prepareToDrink( Bottle anyBottle )
{
     anyBottle.open(); //also works with that Budweisser bottle. Also with champagne.
}

As you can see, not only will it work with any beer Bottle in the house, but also with other kinds of bottles, assuming that the other bottles are derived from the same basic Bottle class.

The definition you found chooses to call the "piece of software" a "client", and the dependency a "service", but elaborate talk of this kind can be misleading at times.

A dependency is really anything that your piece of software needs in order to do its job.  (It depends on it.)  It may be an object, or it may be an interface; but if it was to be an object, then that object would have to be of a specific class, or a class more derived from it, and this would be a bit limiting.  We prefer to use interfaces so that we can pass any class we like, without it having to be derived from a specific class.

So, for example, if we want to also be able to open beer cans, but Can is not derived from Bottle, we can have both Can and Bottle implement the Openable interface, in which case we can do this:

function prepareToDrink( Openable anythingThatSupportsOpening )
{
    anythingThatSupportsOpening.open(); //opens bottles; also opens cans.
}


答:
Here's an example from an angularjs project that is actually being used by large clients you probably do business with.

We have questions that are read in from json (technically, many of them start as xml and undergo a conversion process). The various question types all have different things that need to be added to them based on what our clients want to know. We could put all that "stuff" in the XML/json, but that's a lot of overhead and very error-prone. So instead, we create a "factory" Class for each question type that knows how to take in some initialization data and a question worth of JSON and add all that stuff to it. Then we have another Class whose responsibility is to get the JSON file, look to see what type of question it is, call $injector.$get, to retrieve the factory, initialize the factory and then call the createQuestion() method on each factory.  This allows us to provide infinite flexibility on the types of questions we can parse--to add another, you just register another factory with Angular that knows what to do and nothing else needs to care.

Note that I don't actually provide or implement an Interface. I'm not working in TypeScript, so AFAIK there is no actual way to do that in just plain JavaScript. The presumption is if the injector finds something called questionTypeFactory, it has an init and createQuestion method.

We use the same pattern to synchronize things to audio. Our Json files that define that have a collection of "demoSteps" and each demo step has an "action" property. When the audio framework calls the callback, the callback rifles around in the $injector for actionNameCommand, passes in some initialization data, and calls its execute() method. Again, there's no actual Interface defined, it's simply presumed that if you find something called actionNameCommand nobody put it there without writing it correctly. And we have resharper templates that make it trivial to do so.


问:
What is this algorithm for converting strings into numbers called?
I've been doing some work in Parsec recently, and for my toy language I wanted multi-based fractional numbers to be expressible.  After digging around in Parsec's source a bit, I found their implementation of a floating-point number parser, and copied it to make the needed modifications.

So I understand what this code does, and vaguely why (I haven't worked out the math fully yet, but I think I get the gist).  But where did it come from?  This seems like a pretty clever way to turn strings into floats and ints, is there a name for this algorithm?  Or is it just something basic that's a hole in my knowledge?  Did the folks behind Parsec devise it?

Here's the code, first for integers:

```<code>number' :: Integer -> Parser Integer
number' base =
    do { digits <- many1 ( oneOf ( sigilRange base ))
       ; let n = foldl (\x d -> base * x + toInteger (convertDigit base d)) 0 digits
       ; seq n (return n)
       }
</code>```

So the basic idea here is that digits contains the string representing the whole number part, ie "192".  The foldl converts each digit individually into a number, then adds that to the running total multiplied by the base, which means that by the end each digit has been multiplied by the correct factor (in aggregate) to position it.

The fractional part is even more interesting:

```<code>fraction' :: Integer -> Parser Double
fraction' base =
    do { digits <- many1 ( oneOf ( sigilRange base ))
       ; let base' = fromIntegral base
       ; let f = foldr (\d x -> (x + fromIntegral (convertDigit base d))/base') 0.0 digits
       ; seq f (return f)
</code>```

Same general idea, but now a foldr and using repeated division.  I don't quite understand why you add first and then divide for the fraction, but multiply first then add for the whole.  I know it works, just haven't sorted out why.

Anyway, I feel dumb not working it out myself, it's very simple and clever looking at it.  Is there a name for this algorithm?  Maybe the imperative version using a loop would be more familiar?

答: My Haskell is very rusty, but, from what I can see, this is the usual quick-and-easy method of converting a string to a floating-point number.  Quick and easy, but not a good method for production code that needs accurate numbers.  Each division for each digit in the fraction causes a potential loss of, IIRC, 1/2 of the least-significant bit of the mantissa in accuracy.  I'm not familiar with the internals of Unix and Windows libraries, but I remember seeing the microfiche for portions of the VAX/VMS math libraries back in the 1980s and they used, again if I remember correctly, software-implemented 128-bit arithmetic (which was not supported at that time in the hardware) to ensure the accuracy of their results as computations progressed.</p>


问:
Overriding == for immutable collections
Suppose I have a class that is a readonly collection or immutable objects, e.g.

```<code>public class ReadOnlyInts : IReadOnlyCollection<int>
{
    private readonly IReadOnlyCollection<int> intCollection;
    public ReadOnlyInts(IEnumerable<int> ints)
    {
        intCollection = ints.ToList().AsReadOnly();
    }

    #region IReadOnlyCollection<int> Methods
    // ...
    #endregion
}
</code>```

Now, without some trickery on the part of the consumer neither the intCollection nor its members can change so the type is immutable. Going by the MSDN guidelines, the type should overload ==. However, it is not clear to me that these guidelines are intended to apply to collections as the .Net built in collections do not override even .Equals. I am worried then that overloading == as roughly .SequenceEquals will be unexepected behavior to other consumers.

Is it a good idea for deeply immutable collections to overload ==?

答: If you construct two different ReadOnlyInts, but they have the same content (perhaps created from the same IEnumerable<int> object) do you want them to be equal?  If so then you should overload == and check the contents for equality.  Otherwise it's just a reference comparison which will fail with two different but identical objects.

Title: Overriding == for immutable collections


问:
Find likely candidates for visited locations along GPS track
I'm creating a visualization tool for workout data, specializing on bicycle rides. I'm looking for ways to generate more value from the data that was recorded. Since there usually is a GPS track available I was wondering if and how I could extract possible visited towns or special locations during the trip. I'm especially interested in the possible intended destination of a trip.

Now this is really easy if you have a track that goes from location A to B but my tracks are usually round courses where the start and end location are the same.

Some special cases exist where the destination should be relatively easy to determine. Those are:

There is a location where the recording was paused, thus causing a gap in the recorded data

Recording isn't paused but the location stays the same for a considerable time. The likely candidate for the intended destination would be the longest of such periods.

Assuming we don't encounter one of the above circumstances I'd like to create a list of cities / special locations visited or rode by.

I can imagine narrowing down the search by dividing the track into thirds and only analyze the middle segment, which most likely contains the intended destination.

Now there are APIs available that could give me nearby locations to any given GPS point but asking for the information for every point would cause thousands of requests, since there usually is one GPS point available every second.

Now my question is:

Is there any known algorithm or technique that would decrease the number of requests I would have to send to a location API? If not, what would be a good way to find possible intended locations along a GPS track if the track contains no pauses or hot spots where the location is approximately the same for a extended period. I realize this is the same question as asking for any special location along a segment of a GPS track, which I have no good idea for either.

An example of the desired result would look like this:

A GPS track is uploaded

The algorithm/program returns a list of
locations with name and address, like:

City A, address

City B, address

Restaurant A, address

Also all ideas including how I could structure and group the location data to help with the analysis are appreciated.

答:
The API which gives you nearby locations to a given GPS point must work with some kind of radius, either implied (stated in the documentation) or explicitly passed as a parameter.  Suppose this radius is R.

So, send a request for the first point in the path, and then start skipping subsequent points for as long as you are within R.  Once you reach a point outside R, send your next request, and start counting from that point.  This way, you are not sending unnecessary requests, so the number of requests will be significantly reduced.

If you find that you are still sending too many requests, then increase R.


问:
Bus bunching simulation code
I'm having a peculiar issue to solve. What I am supposed to implement is a bus transit simulation in which there are passengers coming at some random generated time intervals and are added into a queue and they wait for the bus to arrive at bus stops and bus stops there and they board the bus until the queue is empty. It is assumed that every passenger takes exact same time to board the bus. As the queue is empty, the bus moves towards the next bus stop for the same thing. There are several buses and several bus stops. Lets say if a person queue at some bus stop is bigger than the person queue at another bus stop, the bus will take more time to fill at that stop and because of that the successive bus stop will have a larger queue too and again the bus had to wait there for a longer time. This issue will be continued until the buses bunch as a single whole and move just behind each other. Bus are not allowed to cross each other.

I need to implement this in any language. I think python would be fine for this job. Positively thinking to go with Python.

I have tried to break down this problem into parts. So before starting stops are equidistant from each other and person queue is empty. Then the buses start moving and person queue starts increasing and as soon as a bus reach a person queue at a particular bus stop, person queue will decrement to zero and bus will move to the next bus stop. A thing to notice here is person queue is truncated in a manner that each dequeue operation is carried out in a specific amount of time. So if 5 persons are to be removed from the queue, they will take 3 seconds * 5 = 15 seconds for the entire dequeue or truncation of a person queue. The bus on reaching the next bus stop will check whether person queue is empty or not and if not, then it will dequeue until truncated and move ahead. This implementation, when extended for 5 buses and 15 bus stops will lead to bus bunching at some point of time since buses cannot cross each other.

Kindly provide me some ideas to make it as simple as possible because this is something that I need to demonstrate but not use anywhere as an actual implementation.

答:
I don’t think you need to represent individual riders at all, except as numeric aggregates.  Don’t let the fact that, in (British) English, people line up in queues for the bus mislead you about which data structure to use!

What I would suggest is:

A parameterized path representing the bus route, with the bus stops as points along the route.  (If your demonstration is graphical, these can be knots, and you will have a very straightforward translation to a b-spline.)

The position of each bus along the route, represented as a periodic t value along the path.

A number of people on each bus.  You might represent a fixed percentage getting off at each stop, so the number of riders exponentially decays.

A number of people waiting at each stop.  If the stops have a certain population of potential riders and a certain chance that any of them will show up per minute, this could be modeled by a hypergeometric random variable.  What’s important for the demonstration, though, is that the number of people at each stop grow the longer it takes the next bus to arrive (preferably at an asymptotic rate).  You could just roll the dice each minute, add the successes, and get the same result.

Title: Bus bunching simulation code


问:
How can I architect P2P discovery?
I've never really done network programming so this is all new to me. What I'm attempting to make is a Peer to Peer "chat" client. The idea is that anyone can connect to someone whose IP they know. All chat messages are to be distributed to everyone.

What I'm getting stuck on is the peer discovery. What I've done so far is:

App has an IP of a known person (user provided)

Connects to known IP

Known IP provides it's list of known Peers; we store it in peer list

Discovery loop:

Make a local copy of peer list

For each Peer in local peer list

Request Peer list (i.e. step 2 + 3)

If error, remove this peer from original peer list

Otherwise, add new peers to original peer list

Queue another Discovery Loop in 1min

The listening for connections in step 3 and the discovery loop are asynchronous.

The reason a copy is made in the first place is due to some other design decisions for down the road.

The problem is that if I introduce a client with a bad peer on it's peer list, i.e. you can't connect to it, what happens is that this Peer is passed via step 3 when serving the known peer list and then other clients have it in theirs. They propagate this bad peer and later on, during the Discover Loop, remove that peer. But then, they will do another Discover Loop and will receive that Peer from someone else again.

The end result is that bad peer never leaves the network.

One option I can think of is a vague idea of having Peer "health" that each client keeps track of separately so that they can ignore peers provided on someone elses list. However, this would, I think, need to be somewhat "timed" so that when someone disconnects they aren't shut out of the network forever.

The other idea I had was for a broadcast message to all known peers when a bad peer is encountered. However, I didn't like this idea because it leaves it open for someone to make a different client that's job is to poison the network by insisting peers are bad. This would then require me to have peers check that a remove request is genuine by also attempting to connect to his peer immediately.

I'm looking for opinions on the two options above.

答: I personally like the broadcast idea. It may be possible to implement security protocols to minimize the risk of an arp poison attack.</p>

Title: How can I architect P2P discovery?


问:
Which C# data structure should I use to quantify this information?
I am attempting to determine which data structure I should use for the following information:

```<code>        ("Water", 100F, 0F, 0F, 0F, 0F, 0F, 0F, 0F, 0F, 0F, "");
        ("Tuna", 60F, 184F, 30F, .01F, .001F, .064F, .05F, 0F, .011F, .05F, "");
        ("Chicken Breast", 62F, 197F, 30F, .01F, .001F, .027F, .07F, 0F, .013F, .084F, "");
        ("Cheese", 37F, 406F, 24F, .01F, .000F, .027F, .64F, 0F, 0F, .1F, "");
        ("Beef Sausage", 54F, 320F, 12F, .01F, .001F, .013F, .911F, 0F, .003F, .058F, "");
        ("Boiled Eggs", 75F, 155F, 12.5F, .01F, .001F, .010F, .124F, 0F, 0F, .373F, "");
        ("Broccoli", 89F, 34F, 3F, 2.4F, 0F, .021F, .033F, .089F, 0F, 0F, "");
</code>```

Essentially, these are types of food and certain constituent nutritional values and the string on the end is for additional comments.

I want to be able to call the name of the food elsewhere in the code
(i.e. NutritionalData("Tuna") and have it return the nutritional data previously stored in the data structure.

When replying, please bear in mind I am a novice programmer. I looked into Array but that seemed limited to one data type, and these need to be a combination of strings and floats. The first entry will be unique (there won't be two entries for "Tuna", for example), so I was wondering if the Dictionary data type might be best, but I don't know much about it.

Or would this be best as a new class like the following:

```<code>class FoodItem
    {
        string Name;
        float Hydration;
        float Calories;
        float Protein;
        float Fiber;
        float Iron;
        float Magnesium;
        float Sodium;
        float VitaminC;
        float Niacin;
        float Cholesterol;
        string Special;
    }
</code>```

Here is the edited code, Not sure if it works because I haven't figured out how to call a method from outside the class. Yay for self-education.

```<code>class MakeFoodDictionary
{
    public Dictionary<string, FoodItem> foodDictionary = new Dictionary<string, FoodItem>();

    public struct FoodItem
    {
        public string Name;
        public float Hydration;
        public float Calories;
        public float Protein;
        public float Fiber;
        public float Iron;
        public float Magnesium;
        public float Sodium;
        public float VitaminC;
        public float Niacin;
        public float Cholesterol;
        public string Special;
    }

    public FoodItem TempFoodItem;

    public void CreateAllFoods()
    {
        CreateNewFoodItem("Water", 100F, 0F, 0F, 0F, 0F, 0F, 0F, 0F, 0F, 0F, "");
        CreateNewFoodItem("Tuna", 60F, 184F, 30F, .01F, .001F, .064F, .05F, 0F, .011F, .05F, "");
        CreateNewFoodItem("Chicken Breast", 62F, 197F, 30F, .01F, .001F, .027F, .07F, 0F, .013F, .084F, "");
        CreateNewFoodItem("Cheese", 37F, 406F, 24F, .01F, .000F, .027F, .64F, 0F, 0F, .1F, "");
        CreateNewFoodItem("Beef Sausage", 54F, 320F, 12F, .01F, .001F, .013F, .911F, 0F, .003F, .058F, "");
        CreateNewFoodItem("Boiled Eggs", 75F, 155F, 12.5F, .01F, .001F, .010F, .124F, 0F, 0F, .373F, "");
        CreateNewFoodItem("Broccoli", 89F, 34F, 3F, 2.4F, 0F, .021F, .033F, .089F, 0F, 0F, "");
        CreateNewFoodItem("Dry Oats", 8F, 389F, 17F, 10.6F, .005F, .177F, .002F, 0F, .001F, 0F, "");
        CreateNewFoodItem("Ale", 91F, 37F, .2F, 0F, 0F, .007F, .013F, 0F, .001F, 0F, "Inebriation");
        CreateNewFoodItem("Salted Beans", 67F, 127F, 8.67F, 6.4F, .003F, .045F, .238F, .001F, .001F, 0F, "");
        CreateNewFoodItem("Bread", 32F, 278F, 8.4F, 6F, .003F, .081F, .346F, 0F, .004F, 0F, "");
        CreateNewFoodItem("Turnips", 92F, 28F, .9F, 1.8F, 0F, .011F, .067F, .021F, 0F, 0F, "");
        CreateNewFoodItem("Salted Pork", 11F, 748F, 5F, 0F, 0F, .007F, 2.684F, 0F, .002F, .086F, "");
        CreateNewFoodItem("Cabbage", 92F, 25F, 1F, 1.9F, 0F, .012F, .018F, .037F, 0F, 0F, "");
        CreateNewFoodItem("Dried Blueberries", 15F, 317F, 2.5F, 7.5F, .001F, .018F, .003F, .024F, .001F, 0F, "");
        //AddNewFoodToArray(string Name, float Hydration, float Calories, float Protein, float Fiber, float Iron, float Magnesium, float Sodium, float VitaminC, float Niacin, float Cholesterol);
        TempFoodItem = TempFoodItem;
    }

    public void CreateNewFoodItem(string _Name, float _Hydration, float _Calories, float _Protein, float _Fiber, float _Iron, float _Magnesium, float _Sodium, float _VitaminC, float _Niacin, float _Cholesterol, string _Special)
    {
        TempFoodItem = new FoodItem
        {
            Name = _Name,
            Hydration = _Hydration,
            Calories = _Calories,
            Protein = _Protein,
            Fiber = _Fiber,
            Iron = _Iron,
            Magnesium = _Magnesium,
            Sodium = _Sodium,
            VitaminC = _VitaminC,
            Niacin = _Niacin,
            Cholesterol = _Cholesterol,
            Special = _Special
        };
        foodDictionary.Add(_Name, TempFoodItem);
    }
}
</code>```

答: It may be more efficient to store all of the data in an external database and import the data and call each item needed using a loop. </p>


问:
API design pitfalls in C
What are some flaws that drive you nuts in C APIs (including standard libraries, third party libraries, and headers inside of a project) ?  The goal is to identify API design pitfalls in C, so people writing new C libraries can learn from mistakes of the past.

Explain why the flaw is bad (preferably with an example), and try to suggest an improvement.  Although your solution might not be practical in real life (it's too late to fix strncpy), it should give a heads up for future library-writers.

Although the focus of this question is C APIs, problems that affect your ability to use them in other languages are welcome.

Please give one flaw per answer, so democracy can sort the answers.

答:
Functions that take/return compound data types by value, or that use callbacks.

Even worse if said type is a union or contains bit-fields.

From the perspective of a C caller, these are actually OK, but I do not write in C or C++ unless required to, so I am usually calling via an FFI.  Most FFIs do not support unions or bit-fields, and some ( such as Haskell and MLton) cannot support structs passed by value.  For those that can handle by-value structs, at least Common Lisp and LuaJIT are forced onto slow paths -- Lisp's Common Foreign Function Interface must make a slow call via libffi, and LuaJIT refuses to JIT-compile the code path containing the call.  Functions that may call back into the hosts also trigger slow paths on LuaJIT, Java, and Haskell, with LuaJIT not being able to compile such a call.

Title: API design pitfalls in C


问:
Using delete this to free memory in class
Whenever we are writing destructors in C++ (though this concept could apply in other languages) could we just not write

```<code>delete this;
</code>```

and it would delete whatever data is inside of the class? Is this a good or bad idea? If it is bad, would this not delete all the memory we had allocated to the object?

答:
What does a delete expression do?

It invokes the destructor on the pointed-to data.

It frees memory that was allocated with new.

Since a delete will invoke a destructor, delete this inside a destructor makes no sense (I do not know whether this would be an infinite loop, or would be undefined behaviour).

The even more problematic part is that most objects in C++ are not created with the new operator, and therefore should not be explicitly destroyed via delete. Instead, the objects might be local variables that are destroyed when their scope is left – this deterministic destruction enables RAII. Alternatively, the object might be a member of another object. Members will be destroyed after their enclosing object's destructor has run. They do not have to be destroyed explicitly. E.g. assume the following example:

```<code>#include <iostream>

class A
{
public:
  ~A() { std::cout << "~A()\n"; }
};

class B
{
  A _a;
public:
  ~B() { std::cout << "~B()\n"; }
};

int main() {
  B b;
  return 0;
}
</code>```

When the main scope is left, the B b object is destroyed, and its destructor is run. After that, each member is destroyed, so A _a's destructor is executed. Consequently, the output will be

```<code>~B()
~A()
</code>```

If you are using new and delete to manage memory, then it is important to specify who is responsible for making sure an object is deleted. In general, whoever allocated it must also delete it. However, there are some patterns where the object itself is responsible for its own destruction. E.g. an object might be reference-counted, and should delete itself when the reference count drops to zero. (Really, you should be using std::shared_ptr instead.) Or a GUI might have a dialog window class where dialog instances should delete themselves when the user dismisses it.

Body:
What does a delete expression do?

It invokes the destructor on the pointed-to data.

It frees memory that was allocated with new.

Since a delete will invoke a destructor, delete this inside a destructor makes no sense (I do not know whether this would be an infinite loop, or would be undefined behaviour).

The even more problematic part is that most objects in C++ are not created with the new operator, and therefore should not be explicitly destroyed via delete. Instead, the objects might be local variables that are destroyed when their scope is left – this deterministic destruction enables RAII. Alternatively, the object might be a member of another object. Members will be destroyed after their enclosing object's destructor has run. They do not have to be destroyed explicitly. E.g. assume the following example:

#include <iostream>

class A
{
public:
  ~A() { std::cout << "~A()\n"; }
};

class B
{
  A _a;
public:
  ~B() { std::cout << "~B()\n"; }
};

int main() {
  B b;
  return 0;
}

When the main scope is left, the B b object is destroyed, and its destructor is run. After that, each member is destroyed, so A _a's destructor is executed. Consequently, the output will be

~B()
~A()

If you are using new and delete to manage memory, then it is important to specify who is responsible for making sure an object is deleted. In general, whoever allocated it must also delete it. However, there are some patterns where the object itself is responsible for its own destruction. E.g. an object might be reference-counted, and should delete itself when the reference count drops to zero. (Really, you should be using std::shared_ptr instead.) Or a GUI might have a dialog window class where dialog instances should delete themselves when the user dismisses it.


答:
Opaque types that are passed through the interface as type deleted handles. The problem is, of course, that the compiler can't check the user code for correct argument types.

This comes in various forms and flavors, including, but not limited to:

void* abuse

using int as a resource handle (example: the CDI library)

stringly typed arguments

The more distinct types (= cannot be used fully interchangeably) are mapped to the same type deleted type, the worse. Of course, the remedy is simply to provide typesafe opaque pointers along the lines of (C example):

```<code>typedef struct Foo Foo;
typedef struct Bar Bar;

Foo* createFoo();
Bar* createBar();

int doSomething(Foo* foo);
void somethingElse(Foo* foo, Bar* bar);

void destroyFoo(Foo* foo);
void destroyBar(Bar* bar);
</code>```

Title: API design pitfalls in C

Body:
What are some flaws that drive you nuts in C APIs (including standard libraries, third party libraries, and headers inside of a project) ?  The goal is to identify API design pitfalls in C, so people writing new C libraries can learn from mistakes of the past.

Explain why the flaw is bad (preferably with an example), and try to suggest an improvement.  Although your solution might not be practical in real life (it's too late to fix strncpy), it should give a heads up for future library-writers.

Although the focus of this question is C APIs, problems that affect your ability to use them in other languages are welcome.

Please give one flaw per answer, so democracy can sort the answers.

Body:
Opaque types that are passed through the interface as type deleted handles. The problem is, of course, that the compiler can't check the user code for correct argument types.

This comes in various forms and flavors, including, but not limited to:

void* abuse

using int as a resource handle (example: the CDI library)

stringly typed arguments

The more distinct types (= cannot be used fully interchangeably) are mapped to the same type deleted type, the worse. Of course, the remedy is simply to provide typesafe opaque pointers along the lines of (C example):

typedef struct Foo Foo;
typedef struct Bar Bar;

Foo* createFoo();
Bar* createBar();

int doSomething(Foo* foo);
void somethingElse(Foo* foo, Bar* bar);

void destroyFoo(Foo* foo);
void destroyBar(Bar* bar);