问:
Subscript/assignment binary operator in C++
I was designing a kind of a parser when I thought that it would be nice to have an operator overload like this: operator[]=(subscipt_type s, rvalue_type val). For example we have a class:

//collection of Foos
class FooCollection
{
public:

    //assume class Foo is defined
    Foo& operator[]=(int i, const Foo& val);
    //.....
};
```

<p>And we need to assign a subscripted value:</p>

<pre class="lang-cpp prettyprint-override"><code>Foo value;
FooCollection c;
c[42] = value;
</code>```

then the last line of this code will resolve into

c.operator[]=(42,value);
```

<p>The advantage of this operator in comparison to existing <code>Foo& operator[](int i)</code> is that we know the rvalue of assignment during the subscripting, so we can do something that could be unwished in ordinary <code>operator=</code>.</p>

<p>For example, I tried to design a parse tree consisting of polymorphic nodes with minimal interface. This is the basic node class, all other node types are inherited from it:</p>

<pre class="lang-cpp prettyprint-override"><code>class AnyNode
{
public:
    virtual AnyNode& operator=(const AnyNode& op)
    {
        //Takes almost no actions here.
        //Overloaded in each subclass to take some sensible actions
    }

    virtual AnyNode& operator[](int i)
    {
        //Returns special null value of AnyNode type.
    }
};
</code>```

The AnyNode class is not pure virtual, so it's possible to construct AnyNode objects. One of the syntax elements that I try to parse is a python-like list, which may contain heterogenous values and may be subscripted with an integer. A class for it:

class ArrayNode : public AnyNode
{
public:
     AnyNode& operator[](int i)
    {
        //Returns a reference to i-th element
    }
};
```

<p>So what will happen when we try to assign something to the array cell, which was not assigned before and it's concrete type was not defined? <code>AnyNode& operator=(const AnyNode& op)</code> from <code>class AnyNode</code> will be called and no actions will be taken. But I want to know the <code>AnyNode&</code> rvalue just after subscripting, so that it could be possible to deduce it's concrete type with RTTI and take some sensible actions. Subscript/assignment operator could look like this:</p>

<pre class="lang-cpp prettyprint-override"><code>AnyNode& operator[]=(int i, const AnyNode& val)
{
    //AnyNode::getType() is provided and it returns a value of the predefined enum.
    //stor is an underlying container that holds pointers to AnyNode,
    //assume it's possible to reference stor[i].
    //NodeNumber is another subclass of AnyNode.
    switch(val->getType())
    {
    case nodetypeNumber:
        stor[i] = new NodeNumber();//Also we may need to delete stor[i] before new allocation.
        //Process further specific initialization of stor[i].
        break;
    //................
    }
    //Or we could use dynamic_cast instead of switch(val->getType())
}
</code>```

I suppose, such kind of subscipt/assignment operator can be easily and consistently built into language. Moreover, it delimits the pieces of code which execute when the subscripted expression is an lvalue and when it's an rvalue: with it the usual subscript operator should be called only when the subscription is rvalue. Of course, if the proposed operator is not defined, but a operator[] is defined, the code should execute in a usual way.

So my questions  are: what pitfalls could I miss about this operator and why does it not included into the language?
Can it break language consistency in any way or can it bring up any ambiguity into the language?

答:
This composite operator isn't part of the C++ language because nobody has ever made a proper case for including it.

The set of operators supported by C++ is very strongly influenced by the set of operations that you can do on the basic types. It goes so far that all operator symbols in C++ have a meaning for at least some of the primitive types.

The problem with your proposed operator[]= is that, for the primitive types, it doesn't have a more specific meaning than a simple contraction of the already existing operator[] and operator=.

When adding anything to C++, a careful balance must be made between the costs of adding the feature (in compiler complexity) and the benefits of it. In particular, a feature will only be added if it makes something possible that wasn't previously possible, or if it makes it vastly easier to do something, and there is a large demand for that feature.

To be honest, I don't see new operators, or a mechanism to provide overloads for compositions of operators, being added to C++ anytime soon.

The effects of your operator[]= can be obtained as well by using a proxy class, like this:

```<code>class ArrayNode : public AnyNode
{
    class Proxy
    {
        SomeArrayLikeType& stor;
        int i;
    public:
        Proxy& operator=(const AnyNode& val)
        {
            switch(val->getType())
            {
            case nodetypeNumber:
                stor[i] = new NodeNumber();//Also we may need to delete stor[i] before new allocation.
                //Process further specific initialization of stor[i].
                break;
            //................
            }
            return *this;
        }

        const AnyNode& operator AnyNode() {
            return stor[i];
        }
    };

public:
    Proxy operator[](int i) {
        return Proxy(stor, i);
    }
};
</code>```

Body:
This composite operator isn't part of the C++ language because nobody has ever made a proper case for including it.

The set of operators supported by C++ is very strongly influenced by the set of operations that you can do on the basic types. It goes so far that all operator symbols in C++ have a meaning for at least some of the primitive types.

The problem with your proposed operator[]= is that, for the primitive types, it doesn't have a more specific meaning than a simple contraction of the already existing operator[] and operator=.

When adding anything to C++, a careful balance must be made between the costs of adding the feature (in compiler complexity) and the benefits of it. In particular, a feature will only be added if it makes something possible that wasn't previously possible, or if it makes it vastly easier to do something, and there is a large demand for that feature.

To be honest, I don't see new operators, or a mechanism to provide overloads for compositions of operators, being added to C++ anytime soon.

The effects of your operator[]= can be obtained as well by using a proxy class, like this:

class ArrayNode : public AnyNode
{
    class Proxy
    {
        SomeArrayLikeType& stor;
        int i;
    public:
        Proxy& operator=(const AnyNode& val)
        {
            switch(val->getType())
            {
            case nodetypeNumber:
                stor[i] = new NodeNumber();//Also we may need to delete stor[i] before new allocation.
                //Process further specific initialization of stor[i].
                break;
            //................
            }
            return *this;
        }

        const AnyNode& operator AnyNode() {
            return stor[i];
        }
    };

public:
    Proxy operator[](int i) {
        return Proxy(stor, i);
    }
};


问:
How to minimize typos when you code?
I make a lot of typing mistakes when I program. I have a good keyboard writing speed but I try to write faster and in the process end up making typos.

I want to type faster, but make less errors. Can I do something to improve the situation?

答:
Every time I made a typo I copied the offending sentence into a file. After a few months, I analysed all the typos I made, grouped them into categories and gave each names (for example confused-order-letter (lettre for letter) , the missing repeated section (imag(in)ing). I found that having names for each enabled me to better spot errors that occurred in future.

I wrote about my experiences and included my taxonomy of typos on my blog.

ContentLicense: CC BY-SA 3.0

Title: How to minimize typos when you code?


问:
What prevents a race condition on a lock?
I understand the basics of what data races are, and how locks/mutexes/semaphores  help prevent them. But what happens if you have a "race condition" on the lock itself? For example, two different threads, perhaps in the same application, but running on different processors, try to acquire a lock at the exact same time.

What happens then? What is done to prevent that? Is it impossible, or just plain unlikely? Or is it a real race condition waiting to happen?

答:
Simply put the code to get into the critical section is specially designed so a race condition won't violate the mutual exclusion.

Most of the time atomic compare and set loops are used that execute at the hardware level

```<code>while(!CompareAndSet(&lock, false, true));//busy loop won't continue until THIS thread has set the lock to true
//critical section
CompareAndSet(&lock, true, false);
</code>```

In absence of that there are well studied software solutions to enable mutual exclusion.

Body:
Simply put the code to get into the critical section is specially designed so a race condition won't violate the mutual exclusion.

Most of the time atomic compare and set loops are used that execute at the hardware level

while(!CompareAndSet(&lock, false, true));//busy loop won't continue until THIS thread has set the lock to true
//critical section
CompareAndSet(&lock, true, false);

In absence of that there are well studied software solutions to enable mutual exclusion.


答:
If I may suggest:

Get a great keyboard

After reading Jeff's Post about mechanical keyboards I decided to buy myself a mechanical keyboard as well. Not only am I firmly convinced that it speeds up typing and has a great ergonomy, it also noticably reduces typing errors I make.

Secondary Advice

Do you know your keyboard layout? Can you type without looking at the keys? If so, get a keyboard with the labels removed. Lose the dependency, the lack of confidence in where each key is situated. It's daunting at first, and, much like Vim and other rewarding editors, it will pay off greatly in the future.

Tertiary Advice

This is anecdotal, but I have two modes of typing. My regular typing speed, and the fast typing speed. I type fast to increase my regular typing speed. I do not type fast to code fast. I type fast to learn typing faster while I'm typing slower. My advice for you is to not type fast, but to type regularly and improve with dedicated, directed practice.

Title: How to minimize typos when you code?

Body:
I make a lot of typing mistakes when I program. I have a good keyboard writing speed but I try to write faster and in the process end up making typos.

I want to type faster, but make less errors. Can I do something to improve the situation?


问:
Count unique visitors by group of visited places
I'm facing the problem of counting the unique visitors of groups of places.

Here is the situation:

I have visitors that can visit places. For example, that can be internet users visiting web pages, or customers going to restaurants. A visitor can visit as much places as he wishes, and a place can be visited by several visitors. A visitor can come to the same place several times.

The places belong to groups. A group can obviously contain several places, and places can belong to several groups.

Given that, for each visitor, we can have a list of visited places, how can I have the number of unique visitors per group of places?

Example: I have visitors A, B, C and D; and I have places x, y and z.

I have these visiting lists:

```<code>[
 A -> [x,x,y,x],
 B -> [],
 C -> [z,z],
 D -> [y,x,x,z]
]
</code>```

Having these number of unique visitors per place is quite easy:

```<code>[
 x -> 2, // A and D visited x
 y -> 2, // A and D visited y
 z -> 2  // C and D visited z
]
</code>```

But if I have these groups:

```<code>[
 G1 -> [x,y,z],
 G2 -> [x,z],
 G3 -> [x,y]
]
</code>```

How can I have this information?

```<code>[
 G1 -> 3, // A, C and D visited x or y or z
 G2 -> 3, // A, C and D visited x or z
 G3 -> 2  // A and D visited x or y
]
</code>```

Additional notes :

There are so many places that it is not possible to store information about every possible group;

It's not a problem if approximation are made. I don't need 100% precision. Having a fast algorithm that tells me that there were 12345 visits in a group instead of 12543 is better than a slow algorithm telling the exact number. Let's say there can be ~5% deviation.

I have a finite number of visitors and a finite number of places. I don't have so much places (approximately 60 for now, but it can grow to 200) but I have quite many visitors (estimated to 50 millions and this number could grow to 200 millions in the next months).

Is there an algorithm or class of algorithms that addresses this type of problem?

答:
I'm answering my own question because I think I have found a way to avoid storing huge quantities of data. Of course it implies an approximation but, as I said, that is not important to have the exact number of unique visitors.

What I need is a table that maps, for each place, the total number of visits. So, following the example I gave in the question, I would have this:

```<code>[
 x -> 5,
 y -> 2,
 z -> 3
]
</code>```

Then, I store a counter of the total number of unique visitors, which is 3 (and not 4 because B didn't visit anything).

I also store the total number of visits: 10.

To know the (approximate) number of unique visitors, I do a cross-multiplication. I sum their total number of visits and divide that number by the total number of visits. I multiply that result by the total number of unique visitors.

It is equivalent to say: "If a group makes a proportion p of the visits, I suppose it also holds the same proportion p of the unique visitors".

Let's take the groups from the question:

```<code>[
 G1 -> [x,y,z],
 G2 -> [x,z],
 G3 -> [x,y]
]
</code>```

We can get their (approximative) number of unique visitors like this:

```<code>[
 G1 -> ((5+2+3)/10) * 3 = 3
 G2 -> ((5+3)/10) * 3 = 2.4
 G3 -> ((5+2)/10) * 3 = 2.1
]
</code>```

The numbers [3, 2.4, 2.1] are not very far from the real result [3, 3, 2].

What we can say is that:

For the special case of the group that holds all the places, the returned result is not an approximation, it is exact.

For other cases, it works well if all the visitors have the same visit comportment. For example, having some visitors that visit many places only once and some visitors that visit only one place many times won't yield to good results.

The worst case would be that, in a first group all the places have very few different visitors that come many times and, in a second group, there would be many different visitors that only come one time. The number of unique visitors of the first group would be overrated while it would be underrated for the second group.

Body:
I'm answering my own question because I think I have found a way to avoid storing huge quantities of data. Of course it implies an approximation but, as I said, that is not important to have the exact number of unique visitors.

What I need is a table that maps, for each place, the total number of visits. So, following the example I gave in the question, I would have this:

[
 x -> 5,
 y -> 2,
 z -> 3
]

Then, I store a counter of the total number of unique visitors, which is 3 (and not 4 because B didn't visit anything).

I also store the total number of visits: 10.

To know the (approximate) number of unique visitors, I do a cross-multiplication. I sum their total number of visits and divide that number by the total number of visits. I multiply that result by the total number of unique visitors.

It is equivalent to say: "If a group makes a proportion p of the visits, I suppose it also holds the same proportion p of the unique visitors".

Let's take the groups from the question:

[
 G1 -> [x,y,z],
 G2 -> [x,z],
 G3 -> [x,y]
]

We can get their (approximative) number of unique visitors like this:

[
 G1 -> ((5+2+3)/10) * 3 = 3
 G2 -> ((5+3)/10) * 3 = 2.4
 G3 -> ((5+2)/10) * 3 = 2.1
]

The numbers [3, 2.4, 2.1] are not very far from the real result [3, 3, 2].

What we can say is that:

For the special case of the group that holds all the places, the returned result is not an approximation, it is exact.

For other cases, it works well if all the visitors have the same visit comportment. For example, having some visitors that visit many places only once and some visitors that visit only one place many times won't yield to good results.

The worst case would be that, in a first group all the places have very few different visitors that come many times and, in a second group, there would be many different visitors that only come one time. The number of unique visitors of the first group would be overrated while it would be underrated for the second group.


问:
Adding a minimum rectangle overlap threshold
I have a function that works perfectly for detecting whether or not r1 overlaps with r2:

```<code>boolean overlaps( Rectangle r1, Rectangle r2 ) {
    return r1.x < r2.x + r2.width && r1.x + r1.width > r2.x &&
        r1.y < r2.y + r2.height && r1.y + r1.height > r2.y;
}
</code>```

But now I would like to add a minimum threshold so that it would return true if r1 overlaps r2 by at least a given length.

Here's what I have so far but haven't had any luck:

```<code>boolean overlaps( Rectangle r1, Rectangle r2, float threshold ) {
    return r1.x < r2.x + r2.width && r1.x + r1.width > r2.x + threshold &&
        r1.y < r2.y + r2.height && r1.y + r1.height > r2.y + threshold;
}
</code>```

答:
If r.x and r.y is your left-down corner then </p>

```<code>boolean overlaps(Rectangle r1, Rectangle r2, float threshold) {
    boolean leftRight = false;
    if (r1.x < r2.x) {
        if(Math.abs(r1.x-r2.x)<r1.width+threshold) leftRight=true;
    } else {
        if(Math.abs(r1.x-r2.x)<r2.width+threshold) leftRight=true;
    }

    boolean upDown = false;
    if (r1.y < r2.y) {
        if(Math.abs(r1.y-r2.y)<r1.height+threshold) upDown=true;
    } else {
        if(Math.abs(r1.y-r2.y)<r2.height+threshold)  upDown=true;
    }

    return upDown&&leftRight;
}
</code>```

Body:
If r.x and r.y is your left-down corner then

boolean overlaps(Rectangle r1, Rectangle r2, float threshold) {
    boolean leftRight = false;
    if (r1.x < r2.x) {
        if(Math.abs(r1.x-r2.x)<r1.width+threshold) leftRight=true;
    } else {
        if(Math.abs(r1.x-r2.x)<r2.width+threshold) leftRight=true;
    }

    boolean upDown = false;
    if (r1.y < r2.y) {
        if(Math.abs(r1.y-r2.y)<r1.height+threshold) upDown=true;
    } else {
        if(Math.abs(r1.y-r2.y)<r2.height+threshold)  upDown=true;
    }

    return upDown&&leftRight;
}


答:
It is not possible that two (or more) threads acquire lock on the same time. There are few types of synchronization methods for instance:

Active waiting - spin lock

Pseudocode:

```<code>1. while ( xchg(lock, 1) == 1); - entry protocole
</code>```

XCHG is an example of atomic operation (exists on x86 architecture) which first sets new value for a "lock" variable and then returns old value. Atomic means that it can't be interrupt - in above example between setting new value and returning old. Atomic - deterministic result no matter what.

```<code>2. Your code
3. lock = 0; - exit protocol
</code>```

When lock is equal to 0 another thread can enter to critical section - while loop ends.

Thread suspending - for example counting semaphore

There exists two atomic operation .Wait() and .Signal() and we have integer variable lets call it int currentValue.

```<code>Wait():
if (currentValue > 0) currentValue -= 1;
else suspend current thread;

Signal():
If there exists thread suspended by semaphore wake up one of them
Else currentValue += 1;
</code>```

Now solving critical section problem is really easy:

Pseudocode:

```<code>mySemaphore.Wait();
do some operations - critical section
mySemaphore.Signal();
</code>```

Usually your programming thread API should give you ability to specify maximal concurrent threads in semaphore critical section. Obviously there are more types of synchronization in multithreaded systems (mutex, monitors, binary semaphore etc.) but they base on above ideas. One could argue that methods which use thread suspending should be preferred to active waiting (so cpu is not wasted) - it's not always the truth. When thread is being suspended - expensive operation called context switch takes it place. However it's reasonable when waiting time is short ( number of threads ~ number of cores ).

Title: What prevents a race condition on a lock?

Body:
I understand the basics of what data races are, and how locks/mutexes/semaphores  help prevent them. But what happens if you have a "race condition" on the lock itself? For example, two different threads, perhaps in the same application, but running on different processors, try to acquire a lock at the exact same time.

What happens then? What is done to prevent that? Is it impossible, or just plain unlikely? Or is it a real race condition waiting to happen?

Body:
It is not possible that two (or more) threads acquire lock on the same time. There are few types of synchronization methods for instance:

Active waiting - spin lock

Pseudocode:

1. while ( xchg(lock, 1) == 1); - entry protocole

XCHG is an example of atomic operation (exists on x86 architecture) which first sets new value for a "lock" variable and then returns old value. Atomic means that it can't be interrupt - in above example between setting new value and returning old. Atomic - deterministic result no matter what.

2. Your code
3. lock = 0; - exit protocol

When lock is equal to 0 another thread can enter to critical section - while loop ends.

Thread suspending - for example counting semaphore

There exists two atomic operation .Wait() and .Signal() and we have integer variable lets call it int currentValue.

Wait():
if (currentValue > 0) currentValue -= 1;
else suspend current thread;

Signal():
If there exists thread suspended by semaphore wake up one of them
Else currentValue += 1;

Now solving critical section problem is really easy:

Pseudocode:

mySemaphore.Wait();
do some operations - critical section
mySemaphore.Signal();

Usually your programming thread API should give you ability to specify maximal concurrent threads in semaphore critical section. Obviously there are more types of synchronization in multithreaded systems (mutex, monitors, binary semaphore etc.) but they base on above ideas. One could argue that methods which use thread suspending should be preferred to active waiting (so cpu is not wasted) - it's not always the truth. When thread is being suspended - expensive operation called context switch takes it place. However it's reasonable when waiting time is short ( number of threads ~ number of cores ).


问:
Format for getting clear directions on data parameters from users
As part of my job, I regularly get ad-hoc requests from users for snapshots of our very large database. However, there's no fixed format for delivering these and they usually come through in the form of bullet-pointed text, for example:

All customers

All active in last 0-24 months (including non-contactable customers)

All committed

In this instance, "committed" is a flag, and "active/non-contactable" is both a text-based status and a dynamic status based on their last purchase. So this request could be interpreted as:

All customers who made a purchase in the last 24 months, regardless of status

All customers who have a "active" or "non-contactable" status regardless of last purchase.

One of the above and then "either" having a committed flag, or "and" having a committed flag.

I won't labour the point - you see the problem. And it's worth adding that the possible range of parameters is quite large. Normally I have to talk to the requestor and go through a rigmarole of explaining the problem and trying to clarify the requirements.

This situation can't be that uncommon. Is there a more effective way of capturing these details, with a checkbox-style grid or other visual aid? Does anyone have any examples of experience of useful solutions?

答:
This is all part of the inefficiencies, inconveniences and potential for errors that are ad hoc requests. These are all compounded the further away from the data the requester is. Good luck with the "big picture" people.

Early on, I don't see how you're going to avoid this, but as the same person makes other requests and the more requests you get in general, you should start noticing some trends and overlapping of information.

The goal should be to educate others and yourself to the point where these requests (think of them as conversations) can get to the point sooner. You can't get away with knowing nothing about your domain/business. Eventually, they won't expect to have to explain the same things to you over and over.

Data Dictionary - start creating one of these so everyone can get on the same page of what everything means. Business rules may make up part of the definitions. If possible, try to get everyone to use standard terminology. This can be a problem with different departments. This way you can refer to the dictionary early on in its adoption.

Get Background Information

who?  This may determine how careful you have to be and the process you may have to take to accomplish the report. You can send something to the accounting department so they can review and check your figures, but if it is going into a presentation for the head of sales, you ore someone else will need to test.

what? These are the detailed questions about the requirements you're already asking.

when? - Don't forget to ask when they need it. Too many people assume everything is a rush job just because someone just asked. If they are in a hurry, you may need to put some requirements on their time for further questions and preliminary checking of the data.

where/how? - To me this is more about what format they want the request. Returning a set of data to be pulled into a spreadsheet for analysis can be very different than a printed report with a lot of formatting and pretty colors for presentation.

why? - This is very important. Don't let people think this is some kind of push back from you, but to gain more understanding so you can make informed suggestions. Maybe they need to defend why they are using the company's resources and time and I don't know if that is up to you.

Maybe you can make some sort of request document with check boxes for the typical stuff, but really it is going to be a back and forth process until you understand what you want.  Never be surprised as you go through this process that there will be things the requester didn't ask for or know. Sometimes they have to see the report to trigger new ideas.  "I didn't realize we sold that many cars last month. To shorten the report can you aggregate it by make/model?" Happens all the time. And if there is room for one more column, they'll eventually ask you to fill it.

ContentLicense: CC BY-SA 4.0


答:
I play music, and I am pretty sure that typing without errors is not much different than playing a song without making mistakes.

Please have a look at that answer to the above question.
Basically, it is not only sufficient to practice your typing skills, you should try to practice well.

Of course, you rarely practice a single piece of code in order to give a performance ("Carnegie Hall, Sat. 8AM: Quicksort Concerto by D. Knuth"). You are likely to improve your typing skill while writing and committing code:

Next time you have the time (not before a deadline) start writing slowly and try to make no error (no typo). The goal is to write as fast as possible while being perfectly correct. Be mindful of what you are doing in order to break from your current habits.

When you make a typo, don't just correct it (doing so, you will learn to write bad and correct quickly), but erase and retry the whole sequence.

Title: How to minimize typos when you code?


问:
Open source license limitations and compatiblity
I am new to open source licenses and it seems very confusing, therefore need some suggestions. We are developing an application which utilities existing components with following license types:

Apache License v2

LGPL v2.1

MIT License

BSD style license

Mozilla Public License v1.1

Now my concern is:

What kind of distribution limitations our application might have from commercial perspective?

What kind of license possibilities we have for our application? (e.g. Apache, proprietary, GPL, etc.)

Thanks!

答:
Both Apache and LGPL are compatible in the way you are using them: as different components. It would be more complex if you were trying to combine in one component code from several licenses under a single one (although the licenses you use above would allow under some conditions to relicense the code to certain licenses).

What you should do¹ is to include with your program a list of components you use with their licenses and their source code (it can be a download link to your website). If you changed the component, publish your modification under the same license.

Given the above licenses of the plugins used, you may publish your program under any license you choose (all of those mentioned are fine: Apache, proprietary, GPL, etc.) Note that for GPL you should include an exception for the components, so there's no need to relicense them for GPL compatibility.
Mention the components and their licensing where you place your main program license.²

¹ This is actually stricter than what you are required by some of the licenses, but it's good citizenship (and also keeps you on the safe side).

² It may range from mentioning the components license files on a COPYRIGHT file to including the full text of the licenses in a window which is showing your EULA.


问:
Is heap fragmentation a problem in bare-metal arm with g++?
I am converting a project from C to mixed C/C++. It is going quite nice, and the new features are really lightening the work.

The platform is an ARM SAM4, compiler is arm-none-eabi-g++. This is not a safety-related equipment, but still could be left running for months and is not supposed to restart sporadically.

The original C project has managed quite nicely to solve problems without a single malloc call, allocating statically all needed data. For example, arrays with unknown size are allocated to the maximum expected size.

Now I am considering can I get away with using new. For example, all STL containers hold their content in the heap. Just adding a new element to a vector can cause de-allocation of a whole region of the heap and allocation of another one.

Will there be fragmentation issues?

Related:

What is memory fragmentation?

答:
There is no way of telling if heap fragmentation will be a problem in your application. We can't tell, because heap fragmentation is the result of certain usage patterns of the memory (de-)allocator and you have not provided any info on that pattern.

In general, you can expect fragmentation issues if you constantly allocate and deallocate objects with varying sizes and varying lifetimes, such that it would be rare to be able to fit a new memory request into a slot that was recently released or that many memory allocations would leave an unusable small number of bytes unused between them.
Such patterns can be very subtle and they also depend on the allocation strategy used by new/delete. Also note that leaked objects effectively get eternal lifetime as far as the memory management is concerned.

You can try to avoid fragmentation by setting up multiple allocators, so that you can allocate different types of objects from different pools. If all objects in a pool have close to the same size, then fragmentation won't be an issue.

Another option is to try to organize your allocations such that objects with a similar lifetime are allocated close together (in time). That also limits the chances of getting fragmentation, because the objects that are always there will be close together in one part of the heap and the more volatile objects will get allocated from a different part of the heap.

Growing a std::vector<> doesn't cause memory fragmentation, but it does have the nasty side effect that you effectively need double the normal amount of memory while growing the vector. This can be an issue if you only have a limited amount of RAM available.

To avoid this problem, you can use std::vector<>::reserve() to set the allocated memory close to the expected maximum.


答:
If the C code is written in such a way that there are no fragmentation issues then it's 100% possible to write similar code in C++.

You could use std::array instead of std::vector.

I'll add that it seems to me that you're trying to solve a problem that isn't there.

Title: Is heap fragmentation a problem in bare-metal arm with g++?

Body:
I am converting a project from C to mixed C/C++. It is going quite nice, and the new features are really lightening the work.

The platform is an ARM SAM4, compiler is arm-none-eabi-g++. This is not a safety-related equipment, but still could be left running for months and is not supposed to restart sporadically.

The original C project has managed quite nicely to solve problems without a single malloc call, allocating statically all needed data. For example, arrays with unknown size are allocated to the maximum expected size.

Now I am considering can I get away with using new. For example, all STL containers hold their content in the heap. Just adding a new element to a vector can cause de-allocation of a whole region of the heap and allocation of another one.

Will there be fragmentation issues?

Related:

What is memory fragmentation?


问:
Are error variables an anti-pattern or good design?
In order to handle several possible errors that shouldn't halt execution, I have an error variable that clients can check and use to throw exceptions. Is this an Anti-Pattern? Is there a better way to handle this? For an example of this in action you can see PHP's mysqli API. Assume that visibility problems (accessors, public and private scope, is the variable in a class or global?) are handled correctly.

答:
In some dynamic programming languages you can use both error values and exception handling.  This is done by returning unthrown exception object in place of ordinary return value, which can be checked like an error value, but it throws an exception if it isn't checked.

In Perl 6 it is done via fail, which if withing no fatal; scope returns a special unthrown exception Failure object.

In Perl 5 you can use Contextual::Return you can do this with return FAIL.


问:
Property value validations on POCO entities
Sorry in advance if this question is so trivial.

The situation

There is a Customer entity whose ID is limited to two letters (A to Z) in the database.

Also, a user can enter the ID value from a Windows form. I think that the best option is that this form will validate (using the controller) with a regular expression like this ^[a-zA-Z0-9]{2}$ whether the value is valid.

The question(s)

Does the Customer entity should also do the validation when I set
the value of the ID property?

Should this validation be outsourced
if, for example, there is also similar validation in other properties
of the entity?

I think that the answer is that it depends if the property value is a requirement of the user or it is a design decision on the database, but I appreciate your knowledge and experience to guide me on the correct way.

Thanks in advance.

答:
If there is a client application, you don't normally do any data validation in the database unless it would cause the database to throw an error e.g. NULL when a value was expected.

If there are a range of valid values however, it isn't uncommon to store these in the database and then make them available to the client application. This is sometimes known as metadata.

For belt and braces defensive coding, it sounds like having data validation in multiple places is a good idea but should you wish to change this, you'd have to update the logic in both places. Validation is best placed in a single layer (i.e. single source of truth) rather than sprinkled throughout the solution.


答:
Working in a constrained memory environment (something that few of us do these days), it is entirely reasonable to use no heap allocation whatever. And C++ can work very nicely to make that possible.

Yes, the C++ collections for the most part do use the heap, because they are designed to grow without limit. Yes, it is almost impossible to ensure that the heap will never be fragmented, using the default allocator. I would not use it without a lot of prior thought.

This gives you two broad choices. Either stick to non-heap collections (which means std::array), or write your own allocator.

Wrapping existing arrays in std::array brings some benefits, but you will have to decide whether they are worth the effort.

A custom allocator can take advantage of your knowledge of how and when memory should be recovered. That might be by keeping free lists, or by periodic reset, or using pools, or some other strategy. It depends on how valuable the heap is to you.

Regardless, C++ has many other benefits. Perhaps the heap is just one step too far.


问:
Formulate release notes consistently
In my project, I came across understanding that writing release notes is both helpful and necessary. However, it is not required by my management and I keep these files virtually to myself. You could say, I do it for self-organization. For each version of the internal prototyping software, I create a version number and update RELEASE file with the changes that have occurred since the last version. Release notes are classified into lists of new features, bug fixes and remaining limitations (features to be implemented in the next version). As my management does not require this document from me, I keep writing release notes in a free manner.

Now, I am not sure how to best formulate (I hope not be sent to English@SE; I am interested not in grammar features, but in experience of other developers here who do fill in release notes for customers) features that have been implemented. At the moment I use different grammar which is inconsistent between notes. I want to gather experience from other developers.

Do you formulate release notes:

starting with I/we (I/we have integrated/tested/updated some new feature), or

as unpersonalized sentences (some new feature has been integrated/tested/updated), or

as nouns: integration/test/update of some new feature, or

other?

At the moment, I mix all of these styles and by choosing one style, I want to be consistent with the industry standard.

答:
If I may put your question to one side for the moment, my primary beef with release notes is they often seem to be brain dumps.

The reader should be able to see at a glance what they're interested in. They shouldn't have to wade through pages and pages to see if their bug has been fixed, or if that long awaited new feature has finally been completed.

Consider breaking it up into sections:

New features

Major modifications

Minor changes

Bug fixes

To answer your question, keep release notes concise, neutral and impersonal.

Some examples:

Bad: After about 3 weeks of investigation, we finally fixed the calculations module late last night. It was down to an overflow in the AddSummaryTotals routine. It was returning a Long when it should have returned an Int.

Good: Overflow error fixed in calculations module

Bad: Changed the graph colours as Jake in marketing says they don't look good on his laptop

Good: Changed the graph colours to improve contrast

Bad: Stopped the reports printing an extra page at the end. I didn't think it was a major issue but it is fixed now!

Good: Stopped the report printing an extra page at the end

Title: Formulate release notes consistently


答:
There are two important factors you did not mention.

Do you want to keep your source code private, or are you willing to distribute it?

Do you want to make money out of this, or will you compete with someone who does?

The basic breakdown is this. If you make no money out of it and harm no-one then just do your best, acknowledge the work of others and don't worry too much. If you have GPL in the mix you will probably have to distribute your source code (depending on some rather complex rules) but if not, then you can probably keep it private if you want.

If you make money out of your product or services and/or if you may cause damage to someone or compete with someone who does, then you must take competent legal advice. That won't protect you, but it will warn you about the risks and possibly help to mitigate them. You are at risk, even if you don't realise it, and the more money you make the bigger the risk.

If you do distribute your own source code you will run into the licence incompatibility problem. There is no licence you can put on your own source code that will satisfy everyone else. Go figure.

Title: Open source license limitations and compatiblity

Body:
I am new to open source licenses and it seems very confusing, therefore need some suggestions. We are developing an application which utilities existing components with following license types:

Apache License v2

LGPL v2.1

MIT License

BSD style license

Mozilla Public License v1.1

Now my concern is:

What kind of distribution limitations our application might have from commercial perspective?

What kind of license possibilities we have for our application? (e.g. Apache, proprietary, GPL, etc.)

Thanks!


答:
If your validation is done at a database level you're working through layers of code to get there. That's expensive, why pass down data only to find out it's wrong? You may be opening long running pointless transactions impacting every user of the application. Not only that but SQL validation is far less flexible than what you can do in JS/C# or any of the other languages available to you.

I would recommend validating as high up the stack as is possible/sensible (obviously if you have multiple UIs don't write it out several times). UI is good, domain objects is good (although I like to keep these as pocos), BLL is common.

Wherever you put it make sure you're consistent so you can find it later!

Title: Property value validations on POCO entities

Body:
Sorry in advance if this question is so trivial.

The situation

There is a Customer entity whose ID is limited to two letters (A to Z) in the database.

Also, a user can enter the ID value from a Windows form. I think that the best option is that this form will validate (using the controller) with a regular expression like this ^[a-zA-Z0-9]{2}$ whether the value is valid.

The question(s)

Does the Customer entity should also do the validation when I set
the value of the ID property?

Should this validation be outsourced
if, for example, there is also similar validation in other properties
of the entity?

I think that the answer is that it depends if the property value is a requirement of the user or it is a design decision on the database, but I appreciate your knowledge and experience to guide me on the correct way.

Thanks in advance.


问:
How much information about an error should be shown to the user?
Applications can always throw errors. If such an error occurs, the user should be notified, because what he asked the application to do has not succeeded.

However, how much information should the user be given? I think most of us agree on not showing a stack trace (Should a stack trace be in the error message presented to the user?), but I can't find a question about the rest of the error contents or what to show to the user.

For example, a language supporting exceptions (.net, java) has the exception type to share, where the exception occured, and a somewhat clarifying message to go along with the exception. Should this also be hidden from the user? Or should we show this anyway? Or should we show a generic message? or should we show one of a number of messages based on what the underlying exception is?

答:
It depends on who the user is, and what they can do with the information.

Generally, try to show them only useful information about things they can resolve themselves. A 40 line stack trace with a regular expression error at the top is not very useful. Much better would be a message that says Date must be formatted as "yyyy-mm-dd". Anything else, and the user might not know how to respond to the error, and then they might not want to use your application, for fear it will cause more cryptic and frightening errors (and yes, non-technical users are sometimes frightened by stack traces). And that might be bad for business.

For internal applications used by other developers, I'm a little more relaxed about displaying a stack trace, in addition to something more useful, because I know the user can handle seeing a stack trace and will probably know what to do about it.

For non-technical users, the only time I think it would be OK to show them a stack trace is in a critical error situation where you need it to resolve the problem, and they are asked to copy and paste the stack trace and send it to you, although really a much better way to do it is to ask them to send a log file, or better yet, have the application send a log file to the developer, after asking the user for permission to share the file.


答:
what to show to the user.
  Should this also be hidden from the user?

You show the user what is actionable for them.

For example, if you have an error which is caused because of some null pointer exception and more of a bug than user error you don't want full explanation because they can't do anything different.

Or should we show this anyway? Or should we show a generic message?

Showing the exception as the primary error message content is pointless for most users. Perhaps if your target user base is developers you could show the information as the full error all the time (maybe you have an internal application for automated testing). But generally users cannot do anything different even with that knowledge.

should we show one of a number of messages based on what the underlying exception is?

The best strategy is to do the following:

Interpret the error into text which is meaningful for the user.

Part of this is "what can the user do differently?"

If they can't do anything different, say something like "an unexpected error has occurred."

Add an "optional" detailed error description

Allow users to submit the error report (or do this automatically, depending on user base)

Example

It shows the "here's what happened" (unexpected error)

Tells user what to do (reopen Mail, even includes a shortcut to do this)

Also has a "view details" if someone is curious to see the full technical error

Provides notification an error error report is filed (see below)

Note that in some cases you may wish to make the error report be manual vs automatic.

Title: How much information about an error should be shown to the user?

Body:
Applications can always throw errors. If such an error occurs, the user should be notified, because what he asked the application to do has not succeeded.

However, how much information should the user be given? I think most of us agree on not showing a stack trace (Should a stack trace be in the error message presented to the user?), but I can't find a question about the rest of the error contents or what to show to the user.

For example, a language supporting exceptions (.net, java) has the exception type to share, where the exception occured, and a somewhat clarifying message to go along with the exception. Should this also be hidden from the user? Or should we show this anyway? Or should we show a generic message? or should we show one of a number of messages based on what the underlying exception is?


问:
Reporting defects in Agile

   I am working in sprint. At the end of sprint I need to send a defect report per sprint. Considering the below scenario please let me know your views.

Two teams(A & B) are working at different locations in Sprint-2 and I am a tester from Team-A and report the defects for the items developed by Team-A in each sprint

Question

1. I reported few defects in Sprint-2 for the functionality developed by Team-B in previous sprint. Do I have to consider this as observation or defect and report to Team-A?

2. I reported 5 defects of Sprint-2 for the functionality developed by team-A. All the defects are fixed and closed by me in the same sprint. Before the end of sprint I observed 2 defects got reopened for some reason. Now the defect count should be 5 or 7(5+2) should be considered for this sprint?

Thanks

Khan

答:
Something seem wrong:
It sounds like the tester (you) is not a part of the team but is a sort of outside assistent, reporting on errors.

If you think recording all errors helps quality, why stop at bugs that you find as a tester? Why no record bugs that the compiler finds? Why not record unmatched parenthesis or uninitalized variables, which the compiler reports about?

Three rules-of-thumb and one workflow:

Within a Sprint, you do not waste time recording bugs - you fix them.

You do not deliver work with known errors because it is not 'done'.
You don't need to file bugs on workitem N, because the programmer is not 'done' with workitem N. He is only 'done' when everyone agrees it is done, it complies with the definition of done, and there are no errors in it (not that I just said the same thing in 3 different ways).
Only then does the programmer go on to the next workitem. So there is no need to record the erorr.

When dealing with an error, especially from other Sprints or Teams, follow this workflow:

can the programmer fix it in < 4 hours?  If YES, then fix it. Done

if not, can the Team fit it in the current Sprint? If YES, then put it on the Scrumboard and fix it. Done.

If not, take it up with the Product Owner. The error can not be fixed in the current Sprint. Can he place the error as a Product Backlog Item on the Product Backlog to be fixed later? If YES, then put it on the PB.

Last and least desirable option: If it can't be fixed together with the current Sprint, and it can't be postponed, the PO can abort the current Sprint.  The Team moans and then fixes the error.

Title: Reporting defects in Agile


答:
Messages to the users should be treated in the same manner as creating a new exception to throw -- you provide the information they will need to decide what to do.

This will of course depend upon your application and userbase, but it should be your guiding principal -- your intent should be to provide the information needed for the "caller" to determine what, if anything, they can do to sucessfully perform the desired action. If it's something simple like an access error to a file, you give a file path and the message that you couldn't access it.  If it's a null pointer exception, just give a generic error message.

Of course there are going to be more "unable to perform the desired action" messages than there will be ones that the user can actually fix, but that's just life - most exceptions are because we made a mistake, not because the user setup the environment incorrectly.


问:
Constructors, Ignore Arguments
Is it possible to have a constructor in a class, that you can ignore certain arguments/parameters?

For example, I have this constructor

Car(color, make, model, wheels, type, doors)

Could I call this constructor and not include the type parameter?

答: Builder Pattern is exact solution to this problem. Especially if the combination of optional and required parameters get big, which would require tons of different constructors.</p>

Title: Constructors, Ignore Arguments


问:
How to avoid downcasting?
My question is about a special case of the super class Animal.

My Animal can moveForward() and eat().

Seal extends Animal.

Dog extends Animal.

And there's a special creature that also extends Animal called Human.

Human implements also a method speak() (not implemented by Animal).

In an implementation of an abstract method which accepts Animal I would like to use the speak() method. That seems not possible without doing a downcast. Jeremy Miller wrote in his article that a downcast smells.

What would be a solution to avoid downcasting in this situation?

答:
If you have a method that needs to know whether the specific class is of type Human in order to do something, then you are breaking some SOLID principles, particularly :

Open/closed principle - if, in the future, you need to add a new animal type that can speak (for example, a parrot), or do something specific for that type, your existing code will have to change

Interface segregation principle - it sounds like you are generalizing too much. An animal can cover wide spectrum of species.

In my opinion, if your method expects a particular class type, to call it's particular method, then change that method to accept only that class, and not it's interface.

Something like this :

```<code>public void MakeItSpeak( Human obj );
</code>```

and not like this :

```<code>public void SpeakIfHuman( Animal obj );
</code>```

Title: How to avoid downcasting?

Body:
If you have a method that needs to know whether the specific class is of type Human in order to do something, then you are breaking some SOLID principles, particularly :

Open/closed principle - if, in the future, you need to add a new animal type that can speak (for example, a parrot), or do something specific for that type, your existing code will have to change

Interface segregation principle - it sounds like you are generalizing too much. An animal can cover wide spectrum of species.

In my opinion, if your method expects a particular class type, to call it's particular method, then change that method to accept only that class, and not it's interface.

Something like this :

public void MakeItSpeak( Human obj );

and not like this :

public void SpeakIfHuman( Animal obj );


问:
Quadtree with duplicates
I'm implementing a quadtree. For those who don't know this data structure, I am including the following small description:

A Quadtree is a data structure and is in the Euclidean plane
  what an Octree is in a 3-dimensional space. A common use of quadtrees
  is spatial indexing.

To summarize how they work, a quadtree is a collection — let's say of
  rectangles here — with a maximum capacity and an initial bounding box. When trying to insert an element into
  a quadtree which has reached its maximal capacity, the quadtree is
  subdivided into 4 quadtrees (a geometric representation of which will
  have a four times smaller area than the tree before insertion); each
  element is redistributed in the subtrees according to its position,
  ie. the top left bound when working with rectangles.

So a quadtree is either a leaf and has less elements than its capacity, or a tree with 4 quadtrees as children (usually north-west, north-east, south-west, south-east).

My concern is that if you try to add duplicates, may it be the same element several times or several different elements with the same position, quadtrees have a fundamental problem with handling the edges.

For instance, if you work with a quadtree with a capacity of 1 and the unit rectangle as the bounding box:

```<code>[(0,0),(0,1),(1,1),(1,0)]
</code>```

And you try inserting twice a rectangle the upper-left bound of which is the origin:
(or similarly if you try inserting it N+1 times in a quadtree with a capacity of N>1)

```<code>quadtree->insert(0.0, 0.0, 0.1, 0.1)
quadtree->insert(0.0, 0.0, 0.1, 0.1)
</code>```

The first insert will not be a problem:

But then the first insert will trigger a subdivision (because the capacity is 1):

Both rectangles are thus put in the same subtree.

Then again, the two elements will arrive in the same quadtree and trigger a subdivison…

And so on, and so forth, the subdivision method will run indefinitely because (0, 0) will always be in the same subtree out of the four created, meaning an infinite recursion problem occurs.

Is it possible to have a quadtree with duplicates? (If not, one may implement it as a Set)

How can we solve this problem without breaking completely the architecture of a quadtree?

答:
You're implementing a data structure, so you have to make implementation decisions.

Unless the quadtree has something specific to say about uniqueness - and I'm not aware that it does - this is an implementation decision. It's orthogonal to the definition of a quadtree and you can choose to handle it however you want. The quadtree tells you how to insert and update keys, but not whether they have to be unique, or what you can attach to each node.

Making implementation decisions is not reinventing the wheel, at least no more than writing your own implementation in the first place.

For comparison, the C++ standard library offers a unique set, a non-unique multiset, a unique map (essentially a set of key-value pairs ordered & compared only by the key) and a non-unique multimap. They're all typically implemented using the same red-black tree and none are breaking the architecture, simply because the definition of the red-black tree has nothing to say about the uniqueness of keys or the types stored in leaf nodes.

Finally, if you think there's research on this, find it, and then we can discuss it. Maybe there is some quadtree invariant I've overlooked, or some additional constraint that allows better performance.

Title: Quadtree with duplicates


答:
You could add Communicate to Animal. Dog barks, Human speaks, Seal.. uhh.. I don't know what seal does.

But it sounds like your method is designed to
    if(Animal is Human)
      Speak();

The question you may want to ask is, what is the alternative? Its hard to give a suggestion since I don't know exactly what you want to achieve. There are theoretical situations where downcasting/upcasting is the best approach.

Title: How to avoid downcasting?

Body:
My question is about a special case of the super class Animal.

My Animal can moveForward() and eat().

Seal extends Animal.

Dog extends Animal.

And there's a special creature that also extends Animal called Human.

Human implements also a method speak() (not implemented by Animal).

In an implementation of an abstract method which accepts Animal I would like to use the speak() method. That seems not possible without doing a downcast. Jeremy Miller wrote in his article that a downcast smells.

What would be a solution to avoid downcasting in this situation?


答: There is often nothing wrong with using this pattern or that pattern, as long as you use the pattern that everyone else uses. In Objective-C development, the much preferred pattern is to pass a pointer where the method that is called can deposit an NSError object. Exceptions are reserved for programming errors and lead to a crash (unless you have Java or .NET programmers writing their first iPhone app). And this works quite well.</p>

Title: Are error variables an anti-pattern or good design?

Body: In order to handle several possible errors that shouldn't halt execution, I have an error variable that clients can check and use to throw exceptions. Is this an Anti-Pattern? Is there a better way to handle this? For an example of this in action you can see PHP's mysqli API. Assume that visibility problems (accessors, public and private scope, is the variable in a class or global?) are handled correctly.


答:
Downcasting is sometimes necessary and appropriate.  In particular, it's often appropriate in cases where one has objects that may or may not have some ability, and one wishes to use that ability when it exists while handling objects without that ability in some default fashion.  As a simple example, suppose a String is asked whether it is equal to some other arbitrary object.  For one String to equal another String, it must examine the length and backing character array of the other string.  If a String is asked whether it equals a Dog, however, it cannot access the length of the Dog, but it shouldn't have to; instead, if the object to which a String is supposed to compare itself isn't a String, the comparison should use a default behavior (reporting that the other object isn't equal).

The time when downcasting should be regarded as most dubious is when the object being cast is "known" to be of the proper type.  In general, if an object is known to be a Cat, one should use a variable of type Cat, rather than a variable of type Animal, to refer to it.  There are times when this doesn't always work, however.  For example, a Zoo collection might hold pairs of objects in even/odd array slots, with the expectation that the objects in each pair will be able to act upon each other, even if they cannot act upon the objects in other pairs.  In such a case, the objects in each pair would still have to accept a non-specific parameter type such that they could, syntactically, be passed the objects from any other pair.  Thus, even if Cat's playWith(Animal other) method would only work when other was a Cat, the Zoo would need to be able to pass it an element of an Animal[], so its parameter type would have to be Animal rather than Cat.

In cases where downcasting is legitimately unavoidable, one should use it without qualm.  The key question is determining when one can sensibly avoid downcasting, and avoiding it when sensibly possible.

Title: How to avoid downcasting?


答:
In this case, the default implementation of speak() in the AbstractAnimal class would be:

```<code>void speak() throws CantSpeakException {
  throw new CantSpeakException();
}
</code>```

At that point, you've got a default implementation in the Abstract class - and it behaves correctly.

```<code>try {
  thingy.speak();
} catch (CantSeakException e) {
  System.out.println("You can't talk to the " + thingy.name());
}
</code>```

Yes, this means you've got try-catches scattered through the code to handle every speak, but the alternative to this is if(thingy is Human) wrapping all the speaks instead.

The advantage of the exception is that if you have another type of thing at some point that speaks (a parrot) you won't need to reimplement all of your tests.

Title: How to avoid downcasting?

Body:
In this case, the default implementation of speak() in the AbstractAnimal class would be:

void speak() throws CantSpeakException {
  throw new CantSpeakException();
}

At that point, you've got a default implementation in the Abstract class - and it behaves correctly.

try {
  thingy.speak();
} catch (CantSeakException e) {
  System.out.println("You can't talk to the " + thingy.name());
}

Yes, this means you've got try-catches scattered through the code to handle every speak, but the alternative to this is if(thingy is Human) wrapping all the speaks instead.

The advantage of the exception is that if you have another type of thing at some point that speaks (a parrot) you won't need to reimplement all of your tests.


问:
How to define different names for the same type and have the compiler check them?
I would like to define several names for the same type and have the compiler distinguish between them.

My motivation is that different int variables could represent very different units, and I would like the compiler to catch errors in units.

typedef int Speed does not generate any warnings, when assigning to Speed from int. One possible solution is using an enum. Furthermore, the enum "hack" does not let me specify the underlying representation e.g. uint8_t.

Is what I am trying to do a bad practice? How do I achieve it in C++?

Edit:

Grim. I tied using enum Speed {};.

```<code>error: invalid conversion from 'int' to 'Speed' [-fpermissive]
error: no match for 'operator+=' in 'a += b'
</code>```

Those are just a couple of errors I encountered. Enums can't be the right way.

I will think about structs, and if in my case some members and predefined operators can actually make the rest of the code cleaner.

Hmm, here is quite some research, to the point of making my question a duplicate.

答:
You can't really do this in C++, as far as I know.

You might be able to sort of do it, using templates and template metaprogramming, like the Boost library for units of measure that GlenH7 mentioned, but that approach will take a LOT of typing and a lot of pain.  You lose ALL of your predefined operations, and have to reimplement the ones you need, in the template metaprogramming syntax.

What you want is something like the Ada type and subtype system.  Ada allows you to define new types, derived from an existing type, that might have identical ranges, but are not directly assignable or type-compatible, and new subtypes, that are directly assignable and type-compatible.


问:
Apply filter only if not null
My function takes an optional parameter, type, which is used to filter through a collection. However, the filter should only apply if the parameter is passed in (in other words, non-null). If the filter is not passed in, it should not be applied. How can I write my logic to reflect this? What I have now is -

```<code>if( other conditions && ( Type == null || (Type != null && Order.Type == Type ) ) )
    return val += Order;
</code>```

But this feels clunky and wrong. Is there a way I can simplify my logic here?

答:
The OP has stated in a comment that the language used has short-circuiting Boolean operators, so this could be written as:</p>

```<code>if( other conditions && ( Type == null || Order.Type == Type ) )
    return val += Order;
</code>```

Title: Apply filter only if not null

Body:
The OP has stated in a comment that the language used has short-circuiting Boolean operators, so this could be written as:

if( other conditions && ( Type == null || Order.Type == Type ) )
    return val += Order;


问:
What are the advantages and disadvantages of splitting teams by architecture tier rather than by product?
As the title states; what are the advantages and disadvantages of splitting teams by architecture tier rather than by product?

For example:

Organization A has three teams:

Team Web and Front End

Team APIs, Web-Services and Data Stuffs

Team Embedded Stuffs

Organization A teams, over time, have become more specialized in their work rather than being truly full-stack developers.

Organization B has three teams:

Team Product Alpha

Team Product Beta

Team Product Charlie

Organization B has fostered an environment of full-stack developers that are all fairly interchangeable among one-another.

What will Organization A be able to do better (and not so better) than Organization B, and vice versa?

You don't necessarily need to take the examples to heart, as they were just to get the point of my question across.

答:
I would go with what works for the team members you have and/or are able to hire. Sort of let it happen organically. Larger organizations can probably hire enough specialists to handle all the tasks they need. This can also depend on how "agile" you really want to be. If everyone can do everything, you have the most flexibility.

One organization may have the luxury of allowing people to specialize because their projects are very similar. You have all the expertise you need and the workload can be balanced. On the other hand, if this organization has been forced to let people focus on one area because they lack the ability to be proficient in many areas, they will be limited in the types of projects they can do or are forced to hire external help to fill the void or help with the workload.

You really have to keep your documentation and domain knowledge up to date if you're going to let developers work on multiple projects.

We tend to think of programmers that can use many languages and work in all aspects of a project to be higher caliber, but it could also mean they know how to build crap 6 different ways.

Both can work and both can be bad. If I found myself having a team that likes to work in all phases of the stack, there would have to be significant increases in production before I would force them to specialize.


答:
The tier-bound organization runs the risk that decisions will be made based on who will implement them rather on where they should be implemented. For example, design a feature so that the major part of the work will be done in tier X, even though it naturally belongs to tier Y, since the tier Y team happens to have much more workload than the tier X team. These decisions might be correct business-wise, but they still incur technical debt and the project-bound organization can usually depend more purely on technical and architectural reason when making these decisions.

On the other hand, the tier-bound organization has an advantage since contrary to intuition - the borders between projects should be less strict than the borders between tiers. The interaction between tiers should be strict and depend on clearly defined protocol, and having separate teams implement the sides of these interactions force the teams to keep the protocols strict and well defined.

The borders between projects should be less strict since they share code, and sharing code is less dangerous than sharing data. If some code was useful in tier X of project A, it's more likely to be useful in tier X of project B than in tier Y of project A. I mean - how many JavaScript functions from your one-page framework are going to be useful in the database? A tier X developer working on project B might be familiar with that code since they've seen it in project A. A project A developer working on tier Y of the project might be familiar with that code since they've seen it in tier X - but they wouldn't be able to reuse it in tier Y anyways.

Data, on the other hand, must be shared between tiers of the same projects, and since sharing data is dangerous you need more strict borders. Here's where the separation of teams can be beneficial - if the desktop app could use access to some data from the server for a quick and dirty solution, a project-bound developer might be tempted to give it that access(since these programmers control both tiers), but a tier-bound developer will have to request that access from the server team, which are more likely to say no(since they have less need for that particular dirty hack so they are less inclined to corrupt the interface to support it) and force the desktop developer to seek a more proper solution.

Project separation is less important in this regard - there is far less need to share data between projects, and when there is such need it's often done through another tier(e.g. two smartphone apps talking through a server), and even when it's done directly, you need to give very little damn to screw this up with dirty tricks, since the border between projects is clearer than the one between tiers.

Title: What are the advantages and disadvantages of splitting teams by architecture tier rather than by product?

Body:
As the title states; what are the advantages and disadvantages of splitting teams by architecture tier rather than by product?

For example:

Organization A has three teams:

Team Web and Front End

Team APIs, Web-Services and Data Stuffs

Team Embedded Stuffs

Organization A teams, over time, have become more specialized in their work rather than being truly full-stack developers.

Organization B has three teams:

Team Product Alpha

Team Product Beta

Team Product Charlie

Organization B has fostered an environment of full-stack developers that are all fairly interchangeable among one-another.

What will Organization A be able to do better (and not so better) than Organization B, and vice versa?

You don't necessarily need to take the examples to heart, as they were just to get the point of my question across.


答:
It's often cleaner to avoid the null altogether by creating two functions:  one with the filter and one without.  The former can call the latter, like:

```<code>if (Order.Type == Type)
  return nonFilterFunction(...)
</code>```

This style follows the Single Responsibility Principle by having one function do only filtering and one function doing the other stuff.  It allows the compiler and runtime assertions to help you out in verifying programmers are using your code correctly.  It's also easier to reason about because in one function you don't have to worry about Type at all, and in the other one, you can assume or assert that Type is never null and not have to worry about it afterward.

The main drawback is one extra function in your API.  Also, this style is difficult if you have a lot of optional parameters, because you couldn't create a new function for every combination, but there are usually other ways to handle that situation.

Title: Apply filter only if not null

Body:
My function takes an optional parameter, type, which is used to filter through a collection. However, the filter should only apply if the parameter is passed in (in other words, non-null). If the filter is not passed in, it should not be applied. How can I write my logic to reflect this? What I have now is -

```<code>if( other conditions && ( Type == null || (Type != null && Order.Type == Type ) ) )
    return val += Order;
</code>```

But this feels clunky and wrong. Is there a way I can simplify my logic here?

Body:
It's often cleaner to avoid the null altogether by creating two functions:  one with the filter and one without.  The former can call the latter, like:

if (Order.Type == Type)
  return nonFilterFunction(...)

This style follows the Single Responsibility Principle by having one function do only filtering and one function doing the other stuff.  It allows the compiler and runtime assertions to help you out in verifying programmers are using your code correctly.  It's also easier to reason about because in one function you don't have to worry about Type at all, and in the other one, you can assume or assert that Type is never null and not have to worry about it afterward.

The main drawback is one extra function in your API.  Also, this style is difficult if you have a lot of optional parameters, because you couldn't create a new function for every combination, but there are usually other ways to handle that situation.


问:
Do you have your own 'misc utils' library? What part are you most proud of?
I know that many of us maintain our own little personal library with tools and utilities that we use often.

I've had mine since I was 16 years old so it has grown to quite a considerable size. Some of the stuff I've written has since been added to the framework. I wrote my own little implementation of expression trees for use with genetic algorithms long before LINQ, which I quite like and was proud of at the time - of course its pretty useless now. But recently I have been going through it and upgrading to .NET 4.0 and re-kindled an interest.

So I'm curious as to what you use your library for. Maybe we could get some cool ideas going for useful little snippets and share them amongst ourselves.

So my questions are:

Do you have a miscellaneous utility library?

Which part are you most proud of and why?

Give an example of code if you like :-)

答:
I wind up implementing split/join ala Perl in languages that don't have it.

I also have reimplemented atoi and itoa in C more times than I want to think about (embedded systems junk).

ContentLicense: CC BY-SA 2.5


问:
What complexity do DI frameworks add?
The currently most upvoted answer to a very recent question states that

DI containers are an "enterprise software" pattern, used when the object graph is very large and complex. I suspect that 95% of applications do not require it.

which is something I strongly disagree with. Maybe I've got the terminology wrong, but for me DI framework means just "something wiring my objects together". Am I missing something?

I'm using Guice even for really tiny projects (like 10 classes) in order to simplify them. Sure, it's a 400 kB JAR file, but this isn't what I'd care about. For a small project I hardly ever need any configuration and the only "overhead" is adding the @Inject annotation.

So I really wonder, what added complexity do DI frameworks cause?

Update addressing the answers

In a 82 class project, I have

32 @Inject annotations

15 @Singleton and 1 @ProvidedBy annotations

4 Providers (all of which I'd need also without DI as they're my factories)

1 Module containing a single line

0 lines XML !!!

That's all. Sure, it's small project, but exactly this was my point. The additional work was a few words rather than lines.

I'm using solely constructor injection in order to get immutable "easygoing" objects. Whenever a new dependency appears, I add a final field, let Lombok's RequiredArgsConstructor take care of the declaration, and let Guice take care of calling it properly.

答:
I think the main disadvantage of using an IoC container is all the magic it does behind the scenes. (This is also a problem with ORMs, another common magical tool.) Debugging IoC issues is not fun, because it becomes harder to see how and when dependencies are being fulfilled. You can't step through dependency resolution in the debugger.

Containers often make it awkward to configure "class A with one version of a dependency, and class B with a different version", or similar scenarios where abstractions are reused. You can end up in situations where every class has its own interface, even when they mean the same thing. This blocks you from the abstraction power of reusing interfaces.

In my opinion, the really big win you get from IoC is automatic lifestyle management. You can declare components as singletons, per-request singletons, transient instances, and so on - and the container takes care of it all for you. It's considerably harder to set this up using new-expressions. On the other hand, it's still easy to cause resource leaks by mismatching lifestyles.

Some projects use IoC to construct everything in the system - even classes representing business data - with no new keywords. I think this is generally a mistake because it encourages you to write poorly-encapsulated classes and too many interfaces. Your code becomes reliant on IoC. It also seems to be co-morbid with over-testing.

Personally, I generally prefer to go without a container. Instead, I compose objects using new-expressions encapsulated in a composition root. It's easy to see the concrete dependencies of a given class, and when I change a constructor I get compile-time errors, both of which are big maintenance wins. It's also straightforward to to configure separate instances with different components.

My advice, if you want to use an IoC container, is to fulfil your dependencies at the entry
 point to the system, and only use it for your actual dependencies (repositories et al). And remember you can still use dependency injection, and even keep configuration in a single file, without using a container.

Title: What complexity do DI frameworks add?


答:
"In order to handle several possible errors happening, that shouldn't halt execution,"

If you mean that the errors should not halt execution of the current function, but should be reported to the caller in some way - then you have a few options that have not really been mentioned. This case is really more a warning than an error. Throwing/Returning is not an option as that ends the current function. A single error message paramter or return only allows for at most one of these errors to occur.

Two patterns that I've used are:

An error/warning collection, either passed in or kept as a member variable. Which you append stuff to and just keep processing. I personally don't really like this approach as I feel it disempowers the caller.

Pass in an error/warning handler object (or set it as a member variable). And each error calls a member function of the handler. This way the caller can decide what to do with such non-terminating errors.

What you pass to these collections/handlers should contain enough context for the error to be handled "correctly" - A string is usually too little, passing it some instance of Exception is often sensible - but sometimes frowned upon (as an abuse of Exceptions).

Typicial code using an error handler might look like this

```<code>class MyFunClass {
  public interface ErrorHandler {
     void onError(Exception e);
     void onWarning(Exception e);
  }

  ErrorHandler eh;

  public void canFail(int i) {
     if(i==0) {
        if(eh!=null) eh.onWarning(new Exception("canFail shouldn't be called with i=0"));
     }
     if(i==1) {
        if(eh!=null) eh.onError(new Exception("canFail called with i=1 is fatal");
        throw new RuntimeException("canFail called with i=2");
     }
     if(i==2) {
        if(eh!=null) eh.onError(new Exception("canFail called with i=2 is an error, but not fatal"));
     }
  }
}
</code>```

Body:
"In order to handle several possible errors happening, that shouldn't halt execution,"

If you mean that the errors should not halt execution of the current function, but should be reported to the caller in some way - then you have a few options that have not really been mentioned. This case is really more a warning than an error. Throwing/Returning is not an option as that ends the current function. A single error message paramter or return only allows for at most one of these errors to occur.

Two patterns that I've used are:

An error/warning collection, either passed in or kept as a member variable. Which you append stuff to and just keep processing. I personally don't really like this approach as I feel it disempowers the caller.

Pass in an error/warning handler object (or set it as a member variable). And each error calls a member function of the handler. This way the caller can decide what to do with such non-terminating errors.

What you pass to these collections/handlers should contain enough context for the error to be handled "correctly" - A string is usually too little, passing it some instance of Exception is often sensible - but sometimes frowned upon (as an abuse of Exceptions).

Typicial code using an error handler might look like this

class MyFunClass {
  public interface ErrorHandler {
     void onError(Exception e);
     void onWarning(Exception e);
  }

  ErrorHandler eh;

  public void canFail(int i) {
     if(i==0) {
        if(eh!=null) eh.onWarning(new Exception("canFail shouldn't be called with i=0"));
     }
     if(i==1) {
        if(eh!=null) eh.onError(new Exception("canFail called with i=1 is fatal");
        throw new RuntimeException("canFail called with i=2");
     }
     if(i==2) {
        if(eh!=null) eh.onError(new Exception("canFail called with i=2 is an error, but not fatal"));
     }
  }
}


问:
How to transition from "help vampire" to "developer"?
I've been a computer enthusiast my entire life, but didn't first start programming (web development) until I began College. It is now four years later - I am about to graduate, have had a handful of full-time internships and part-time work, all revolving around web dev... But I still find myself more often than not seeking out help, tutorials or stackexchange answers to my questions instead of working out problems entirely on my own.

I hear the term "help vampire" -- someone who asks/seeks help with their problems rather than work through issues themselves -- and while that isn't true for me a hundred percent, I find my threshold of getting "frustrated" when trying to accomplish something is quite low and it doesn't take long once I've found a problem to start searching online for a solution, as opposed to work one out myself.

I am certainly able to do my work, but I want to know how I can actually learn to THINK and REMEMBER like a developer, as opposed to relying on online answers as a crutch. It's a nasty habit and I really feel like it's limiting my development potential, speed, flexibility and adaptation to new languages/environments.

TL;DR: How did you transition from seeking help (whether in the form of Q&A's, plugins, tutorials, code-inspecting, etc) to developing solutions (answering the Q&A's, writing your own plugins, creating the tutorials, etc)?

答:
I have been developing for .NET for almost 10 years. I still ask questions every single day. I still read every single day. I still question my assumptions and seek out better solutions every single day.

Searching out proven solutions is better than working things through and reinventing the wheel. There is already too much of that going on in software development.

I would say you should keep sucking up that knowledge and keep searching for what others have done every time you face an unfamiliar problem. There is nothing wrong with learning from the wisdom of others. You will know you are a good senior developer when you have learnt to smell design problems in advance and you question rather than just follow.

The fact is though, in this industry there will always be more that you don't know than you DO know.


问:
Swing component name suggestion for a specific interface
As a university project, I have to replicate Raptor. A flowchart interpreter. The interface looks like this

But as I am not a experienced swing developer, I don't have much idea about which swing components to use for which part.

I know:

The whole thing is a JFrame.

There is MenuBar on the top.

ToolBar exactly beneath it.

Question 1: Am I right?

Question 2: What component should I use for left hand side symbols and rest of the part named main in the picture? What you would have used?

Note 1: We can drag and drop the symbols from Symbols to main.

Note 2: I am not looking for any code. I just want direction. As there are always so many options in Java. It's easy to get confused easily. I researched a lot, but found nothing specific as it is mostly a design issue.

答:
It depends on how complex and fancy (if you will) you want your application to be. I would use JPanels to represent the components (start, end, process, etc).

You can use a JPanel with a custom background (in your case, these would be the shapes of your operations. Look up on how to make an image as a background of your JPanel for more information) and no borders. The advantage of using a JPanel would be that you can actually attach events to it more easily.

You can use JTextAreas to write the content of the shapes, you could capture click events on the JPanel and provide access to the JTextArea for editing.

The major problem I foresee is the drawing of lines. The easiest (I think) would be to store a list of coordinates of where the lines are (also assuming slanting lines will need to be broken down into two lines). Before drawing a new line, you check to see if you will have any intersections and if you do, you maybe use a different colour for the line so that you do not cause confusion.


问:
Design Patterns for Javascript
A lot of web frameworks have a MVC-style layout to code and approaching problems. What are some good similar paradigms for JavaScript? I'm already using a framework (jQuery) and unobtrusive js, but that still doesn't address the problem I run into when I have more complex web apps that require a lot of javascript, I tend to just end up with a bunch of functions in a single, or possibly a few files. What's a better way to approach this?</p>

答:
some people don't realize that JS is fully object oriented. You can create something that works just like a class:

```<code>function Car() {
    this.publicField = "bad";
    var privateField = "good";
    var self = this;

    this.publicMethod = function() {
        alert("I can access " + this.publicField + " and " + privateField);
    }

    function privateMethod() {
        alert("I can access " + self.publicField + " and " + privateField);
    }
}
</code>```

you can instantiate those classes:

```<code>var car = new Car();
</code>```

and it supports inheritance:

```<code>function Vehicle() { /* define class */ }

function Truck() { /* define class */ }
Truck.prototype = new Vehicle();
</code>```

and can even add methods to existing classes:

```<code>Array.prototype.remove = function() {
}
</code>```

If you'd like to learn more about JavaScript's OO support, I highly recommend the Rhino book.

Title: Design Patterns for Javascript

Body:
some people don't realize that JS is fully object oriented. You can create something that works just like a class:

function Car() {
    this.publicField = "bad";
    var privateField = "good";
    var self = this;

    this.publicMethod = function() {
        alert("I can access " + this.publicField + " and " + privateField);
    }

    function privateMethod() {
        alert("I can access " + self.publicField + " and " + privateField);
    }
}

you can instantiate those classes:

var car = new Car();

and it supports inheritance:

function Vehicle() { /* define class */ }

function Truck() { /* define class */ }
Truck.prototype = new Vehicle();

and can even add methods to existing classes:

Array.prototype.remove = function() {
}

If you'd like to learn more about JavaScript's OO support, I highly recommend the Rhino book.


问:
Alternatives to foreach iterators involving ref and out
I am trying to make a flexible particle system for my XNA game, and I've got these interfaces:

```<code>public interface IParticle : IUpdateable
{
    bool Alive { get; }
    float Percent { get; }
}

public interface IParticleEffect<T>
    where T : IParticle
{
    void Apply(GameTime time, ref T particle);
}

public interface IParticleEmitter<T> : IUpdateable
    where T : IParticle
{
}

public interface IParticleRenderer<T> : IDrawable
    where T : IParticle
{
}
</code>```

The idea behind this system is that the client code only needs to derive from IParticle, then make a compatible subclass from IParticleEmitter and IParticleRenderer, and everything else just automagically works behind the scenes. (I'm actually in the middle of writing everything at the moment, but the latter two would have an abstract base class available.)

Anyways, some particle systems like to use mutable structs for optimization purposes, and that's perfectly reasonable. My system only provides the skeleton, and if the client decides that "Hey, structs are the way to go!", then my system should support whatever the client code throws at it. This is why my IParticleEffect.Apply() method takes a particle by ref -- it's cheaper to pass a struct by reference than it is to copy it.

Unfortunately, it breaks when collections are involved, because the foreach iterator doesn't play nicely with objects passed by ref or out. Eric Lippert explains why here.

So, now I have a design decision to make:

Completely disregard structs, and change my constraint to where T: class, IParticle. This potentially hurts future optimizations, but makes it much easier to work with collections.

Change anything that uses ICollection<T> or IEnumerable<T> to IList<T> so I can manually poll it via an indexer. This makes it potentially more powerful, but at the cost of using a deeper interface (list) to store my objects.

Something else

I hope this question isn't too "it depends", but I am curious as to what strategies I can apply here to make it work the way I want.

EDIT: I realized that I could also include a local variable such as:

```<code>foreach (var particle in SomeParticleCollection)
{
    var p = particle;
    SomeEffect.Apply(ref p);
}
</code>```

However, p would still have the net effect of copying it, which is also not ideal.

答:
Premature optimisation is evil.

Drop the structs - go for flexible design. Your initial design seems like you're allowing for flexibility/extensibility. Until you hit performance concerns, stick with the flexible architecture. You'd need to do serious performance profiling to convince everyone that passing structs versus objects is the biggest performance drain in your code - what about the rendering, update logic, AI etc?

Here's an article about whether/how to optimise game programming architectures for performance that I found a good read: http://gameprogrammingpatterns.com/architecture-performance-and-games.html


答:
Are you sure that you really need such a kind of optimization(ref T)? Have you considered analogous systems or mocked your own? Premature optimization is worse than none at all - you end with decisions that are not obvious at best and incomprehensible at worst.

ref T denotes that the referenced value could be changed by the function. And I don't think that it is a normal behaviour for IParticleEffect<T>. It looks strange.

You are defining your own system and any extraneous particle system will have to be specially plugged into it. At worst case if you find that structure copying greatly reduces the performance you could try to wrap it into some class variable.

```<code>public class ParticleStructWrapper<T> : IParticle
 where T: struct, IParticle
{
   T _Particle;
   public ParticleStructWrapper(T particle) {...}

   public Boolean IsAlive { get {return this._Particle.IsAlive;}}
   ...
}
</code>```

It will still cause a copying for the constructor but if you will use it multiple times the net effect will be small.

But if your original particles must be changed in IParticleEffect then you should either use your original solution (despite that it is not very straightforward) or create more sophisticated proxy.

AFTER

the intent was to have the effect modify the particle

The main idea behind structs is that they allow simple passing by value - for structs with only struct fields such passing makes actual deep copy. With such structs you don't have to fear that someone changes it inside the method, because your original structure is completely unaffected. For small structures copying by value and subsequent use are also faster due to the fact that structures are located on the stack.

You can't change those external particle systems, but you could recommend their developers to read http://msdn.microsoft.com/en-us/library/ms229017(v=vs.110).aspx, https://stackoverflow.com/questions/441309/why-are-mutable-structs-evil.

P.S.: It is quite possible that they have already considered all pros and cons between classes and structs, just their solution isn't the most user friendly, or the particles are designed to be immutable.

Title: Alternatives to foreach iterators involving ref and out

Body:
I am trying to make a flexible particle system for my XNA game, and I've got these interfaces:

```<code>public interface IParticle : IUpdateable
{
    bool Alive { get; }
    float Percent { get; }
}

public interface IParticleEffect<T>
    where T : IParticle
{
    void Apply(GameTime time, ref T particle);
}

public interface IParticleEmitter<T> : IUpdateable
    where T : IParticle
{
}

public interface IParticleRenderer<T> : IDrawable
    where T : IParticle
{
}
</code>```

The idea behind this system is that the client code only needs to derive from IParticle, then make a compatible subclass from IParticleEmitter and IParticleRenderer, and everything else just automagically works behind the scenes. (I'm actually in the middle of writing everything at the moment, but the latter two would have an abstract base class available.)

Anyways, some particle systems like to use mutable structs for optimization purposes, and that's perfectly reasonable. My system only provides the skeleton, and if the client decides that "Hey, structs are the way to go!", then my system should support whatever the client code throws at it. This is why my IParticleEffect.Apply() method takes a particle by ref -- it's cheaper to pass a struct by reference than it is to copy it.

Unfortunately, it breaks when collections are involved, because the foreach iterator doesn't play nicely with objects passed by ref or out. Eric Lippert explains why here.

So, now I have a design decision to make:

Completely disregard structs, and change my constraint to where T: class, IParticle. This potentially hurts future optimizations, but makes it much easier to work with collections.

Change anything that uses ICollection<T> or IEnumerable<T> to IList<T> so I can manually poll it via an indexer. This makes it potentially more powerful, but at the cost of using a deeper interface (list) to store my objects.

Something else

I hope this question isn't too "it depends", but I am curious as to what strategies I can apply here to make it work the way I want.

EDIT: I realized that I could also include a local variable such as:

```<code>foreach (var particle in SomeParticleCollection)
{
    var p = particle;
    SomeEffect.Apply(ref p);
}
</code>```

However, p would still have the net effect of copying it, which is also not ideal.

Body:
Are you sure that you really need such a kind of optimization(ref T)? Have you considered analogous systems or mocked your own? Premature optimization is worse than none at all - you end with decisions that are not obvious at best and incomprehensible at worst.

ref T denotes that the referenced value could be changed by the function. And I don't think that it is a normal behaviour for IParticleEffect<T>. It looks strange.

You are defining your own system and any extraneous particle system will have to be specially plugged into it. At worst case if you find that structure copying greatly reduces the performance you could try to wrap it into some class variable.

public class ParticleStructWrapper<T> : IParticle
 where T: struct, IParticle
{
   T _Particle;
   public ParticleStructWrapper(T particle) {...}

   public Boolean IsAlive { get {return this._Particle.IsAlive;}}
   ...
}

It will still cause a copying for the constructor but if you will use it multiple times the net effect will be small.

But if your original particles must be changed in IParticleEffect then you should either use your original solution (despite that it is not very straightforward) or create more sophisticated proxy.

AFTER

the intent was to have the effect modify the particle

The main idea behind structs is that they allow simple passing by value - for structs with only struct fields such passing makes actual deep copy. With such structs you don't have to fear that someone changes it inside the method, because your original structure is completely unaffected. For small structures copying by value and subsequent use are also faster due to the fact that structures are located on the stack.

You can't change those external particle systems, but you could recommend their developers to read http://msdn.microsoft.com/en-us/library/ms229017(v=vs.110).aspx, https://stackoverflow.com/questions/441309/why-are-mutable-structs-evil.

P.S.: It is quite possible that they have already considered all pros and cons between classes and structs, just their solution isn't the most user friendly, or the particles are designed to be immutable.