问:
Which version of Java should I use for a desktop application to reach the most users?
Am I correct to assume that most end users are using an older version than Java 8? Since I do not want to force people to upgrade in order to use my application, should I plan it to use Java 7 or even 6 from the start, even if that means that I can't apply the benefits of the newer versions for myself as a developer?</p>

答:
Relying on an installed JRE to be correct doesn't make sense outside of a controlled corporate environment where all the desktops are locked to a specific version. In which case, you should ask this question of the person who controls that environment.

For a mass-market Java desktop application, you should use an installer or launcher that bundles the JRE you want them to be using, or set up Java Web Start (JAWS).

Note that if you actually physically distribute a bundled JRE, you have to comply with the license terms. I am not a lawyer, but those shouldn't be problematic for most purposes. If you are in a situation where you have a legal team, you should of course run it past them.

For a developer or other technically-oriented tool, it is generally preferable to publish the jars on Maven Central, so distribution and download is entirely automated. This is one case where sticking to older Java versions is something of an advantage, as it enables their use in corporations locked down to an older version.

But I wouldn't worry about that too much for a project started today.

Finally, if all the above is too much work, you can just publish the source on github or bitbucket and let the user build it themselves.


问:
Two dimensional matrix-like data type using lists and/or mutable lists
I am trying to think of an implementation of a two dimensional matrix-like data type.

Normally I would take an array of arrays but I'm bound to a relatively low language level which only provides lists and mutable lists, because this is part of (but not an exercise itself, I could simply use an inefficient solution) a software project at university. In this, we are only allowed to use a specific language level.

So of cause I could take a list of mutable lists and, in search of an item in row n and column m, get the m-th mutable list and go throught it until position n. But isn't there a better solution than going through the whole list?

答:
Since you need constant size, and access elements by their indexes, I'd say go with 1-dimensional array of WIDTH*HEIGHT size. You can just translate indexes like matrix[x+y*WIDTH] or build a wrapper class to do it like matrix.get(x, y) - that way you don't have to track width, and you can add boundary checks.

Access by index will have a constant time (O(1)) performance.

ContentLicense: CC BY-SA 3.0


问:
Scrum - how to carry over a partially complete User Story to the next Sprint without skewing the backlog
We're using Scrum and occasionally find that we can't quite finish a User Story in the sprint in which it was planned. In true Scrum style, we ship the software anyway and consider including the User Story in the next sprint during the next Sprint Planning session. Given that the User Story we are carrying over is partially complete, how do we estimate for it correctly in the next Sprint Planning session? We have considered:

a) Adjusting the number of Story Points down to reflect just the work which remains to complete the User Story. Unfortunately this will mess up reporting the Product Backlog.

b) Close the partially-completed User Story and raise a new one to implement the remainder of that feature, which will have fewer Story Points. This will affect our ability to retrospectively see what we didn't complete in that sprint and seems a bit time consuming.

c) Not bother with either a or b and continue to guess during Sprint Planning saying things like "Well that User Story may be X story points, but I know it's 95% finished so I'm sure we can fit it in."

答:
The first question to ask is What does a Story Point mean? If you define a story point as "How much work engineering gets done", then any answer will do. However if you define a story point as "How much value is delivered to the business", then it becomes important to not give credit until a story is 100% completed, accepted and delivered 100%. Modifying story points after a sprint based on what was completed will only hide the real problem: a) there wasn't a clear understanding of the story, b) the story was too coarsely defined, c) the story lacked measurable acceptance criteria, d) not a deep enough understanding of the tasks or dependencies to complete the story, e) understated the effort to test the story, f) pulled down too many story points, or g) ...insert your reason here... </p>

<p>The goal of agile is to be flexible while being predictable. The best way to be consistent, in my opinion, is to figure out what went wrong without modifying original story estimates.  </p>

Body:
The first question to ask is What does a Story Point mean? If you define a story point as "How much work engineering gets done", then any answer will do. However if you define a story point as "How much value is delivered to the business", then it becomes important to not give credit until a story is 100% completed, accepted and delivered 100%. Modifying story points after a sprint based on what was completed will only hide the real problem: a) there wasn't a clear understanding of the story, b) the story was too coarsely defined, c) the story lacked measurable acceptance criteria, d) not a deep enough understanding of the tasks or dependencies to complete the story, e) understated the effort to test the story, f) pulled down too many story points, or g) ...insert your reason here...

The goal of agile is to be flexible while being predictable. The best way to be consistent, in my opinion, is to figure out what went wrong without modifying original story estimates.


答:
Java 6 is unsupported by Oracle, so don't use that.
Java 7's support ends on April 15th, so you know.
Just use Java 8 and save yourself the hassle.

See Oracle's support roadmap for more info.

Title: Which version of Java should I use for a desktop application to reach the most users?

Body: Am I correct to assume that most end users are using an older version than Java 8? Since I do not want to force people to upgrade in order to use my application, should I plan it to use Java 7 or even 6 from the start, even if that means that I can't apply the benefits of the newer versions for myself as a developer?</p>


问:
Is it wise for a high level developer to spend time studying assembly?
It is clear that the knowledge of low level stuff is very important in our work.

But in a situation where you're already developing commercial software on a high level, and when you already have a chosen direction but don't have any assembly skill, isn't it more reasonable to focus on studying stuff related to your direction? Or is there a reason you should spend some time to learn the low-level basics anyway?

When is it too late, and when it is not? And if it is not too late, then how would one go about learning optimally (in the sense of not spending excessive time to get some depth and understanding)?

答: I don't know how much use studying assembly would be. But at the very least doing some programming in a language like C would be beneficial. I have recently had to do some programming in C and I have found it to be rather enlightening. C removes much of the abstraction that is present in higher level languages. Those abstractions do not come without a cost. You have to manage more of the lower level details in C, where as in a higher level language those details are being managed for you. By doing some programming in C you will have to become aware of those details. So when you are back in your everyday language, you will still have that awareness and will better appreciate what is actually happening. That should help to make you a better programmer.</p>

ContentLicense: CC BY-SA 2.5


问:
Estimating run time of algorithm
For instance if i have an algorithm that is O(n2) and it will run for 10 seconds for a problem size of 1000. Now if i were to double the problem size to 2000 i want to know the approximate run time in seconds. I know the answer for it but i want to understand the logic on how to get to the answer. So here is what i am thinking.

```<code>N = 1000 , Therefore 1000^2 = 10 seconds
N = 2000,  Therefore (2*1000)^2, // stuck here
</code>```

Now i am not sure i mean i know it will be 40 seconds because 2 to the power of 2 is 4 and then you multiply the 10 seconds by 4 and get 40 seconds but not entirely sure if this is right thinking. Was wondering if someone can break it down in simple terms?

答:
Complexity classes such as O(n) or O(n²) are not meant to calculate actual running time. Instead, they are meant to compare how different algorithms scale when we change the input size.

For example, here we have two algorithms that apply frobnicate(a, b) to each matching item:

```<code>void algorithm1(Set<int> items) {
  for (int i in items) {
    for (int j in items) {
      if (i == j) {
        frobnicate(i, j);
      }
    }
  }
}

void algorithm2(Set<int> items) {
  for (int i in items) {
    frobnicate(i, i);
  }
}
</code>```

Obviously, the 1st algorithm has O(n²) complexity while the second is O(n). Therefore, we can conclude that algorithm2 scales better for large inputs. But here is another O(n) algorithm:

```<code>void algorithm3(Set<int> items) {
  sleep(9 seconds);
  for (int i in items) {
    sleep(1 millisecond);
    frobnicate(i, i);
  }
}
</code>```

This scales just as well as algorithm2 but will always be slower! In fact, the O(n²) algorithm1 will outperform this algorithm for small inputs! Because algorithm3 has a fixed 9-second overhead, we can't plug different numbers into the O(n) complexity formula to find out how long a different input size will take.

Example:

```<code>n=1000 => algorithm3 takes 10 seconds
n=2000 => algorithm3 takes 11 seconds, not 20 seconds!
</code>```

In reality, the running time is not possible to reliably calculate. Even if you can figure out a cost for each atomic operation, hardware quirks such as cache boundaries will get in your way. The only reliable option is to do statistical sampling over different input sizes, and then fit an estimation function matching the expected complexity class to the collected data.

Let's assume we have a run time estimation function (!= complexity class) of f(n) = a·n² + b·n + c, and let's assume that b = c = 0 for simplicity (i.e. no linear factors, no constant overhead). Then, we can calculate the parameter a from the data point f(1000) = 10 seconds:

```<code>10 seconds = f(1000)
           = a·1000²
           = a·1000000
 <=> a = 10/1000000 seconds = 1/100000 seconds
</code>```

Therefore, f(n) = n²/100000 seconds. If we plug in n = 2000, we get

```<code>f(2000) = 2000²/100000 seconds
        = 4000000/100000 seconds
        = 40 seconds
</code>```

This is consistent with the shortcut that if we multiply the input size by n (here n = 2), the output is increased by n² (here n² = 4).

Title: Estimating run time of algorithm

Body:
Complexity classes such as O(n) or O(n²) are not meant to calculate actual running time. Instead, they are meant to compare how different algorithms scale when we change the input size.

For example, here we have two algorithms that apply frobnicate(a, b) to each matching item:

void algorithm1(Set<int> items) {
  for (int i in items) {
    for (int j in items) {
      if (i == j) {
        frobnicate(i, j);
      }
    }
  }
}

void algorithm2(Set<int> items) {
  for (int i in items) {
    frobnicate(i, i);
  }
}

Obviously, the 1st algorithm has O(n²) complexity while the second is O(n). Therefore, we can conclude that algorithm2 scales better for large inputs. But here is another O(n) algorithm:

void algorithm3(Set<int> items) {
  sleep(9 seconds);
  for (int i in items) {
    sleep(1 millisecond);
    frobnicate(i, i);
  }
}

This scales just as well as algorithm2 but will always be slower! In fact, the O(n²) algorithm1 will outperform this algorithm for small inputs! Because algorithm3 has a fixed 9-second overhead, we can't plug different numbers into the O(n) complexity formula to find out how long a different input size will take.

Example:

n=1000 => algorithm3 takes 10 seconds
n=2000 => algorithm3 takes 11 seconds, not 20 seconds!

In reality, the running time is not possible to reliably calculate. Even if you can figure out a cost for each atomic operation, hardware quirks such as cache boundaries will get in your way. The only reliable option is to do statistical sampling over different input sizes, and then fit an estimation function matching the expected complexity class to the collected data.

Let's assume we have a run time estimation function (!= complexity class) of f(n) = a·n² + b·n + c, and let's assume that b = c = 0 for simplicity (i.e. no linear factors, no constant overhead). Then, we can calculate the parameter a from the data point f(1000) = 10 seconds:

10 seconds = f(1000)
           = a·1000²
           = a·1000000
 <=> a = 10/1000000 seconds = 1/100000 seconds

Therefore, f(n) = n²/100000 seconds. If we plug in n = 2000, we get

f(2000) = 2000²/100000 seconds
        = 4000000/100000 seconds
        = 40 seconds

This is consistent with the shortcut that if we multiply the input size by n (here n = 2), the output is increased by n² (here n² = 4).


问:
MVC like design with interfaces: How to handle basic objects?
I have an (android) application and decided that the presentation layer will get data only through strict interfaces from the controller. I am at the point where some basic objects need to be passed to the presentation layer, but the objects itself must be in strict read-only mode, because all changes will be handled by the controller.

To make a simple example, imagine a ToDo-App, where the screen needs to display a list of todo items.

The Todo-Item has the fields "title" and "content" with respective getters and setters. Even if I pass an unmodifiable list, the objects in it can be changed. I can think of these alternatives:

put controller and data in one package and make the setters protected.

add an interface to the todo item containing only the getters and passing these objects.

add an interface only to the controller and put all getters there.

for 1)

```<code>public class TodoItem {
    private String title; private String content;
    public String getTitle() ...
    protected String setTitle(..) ...
}
</code>```

for 2)

```<code>public interface ITodoItem {
    public String getTitle();
}

public class TodoItem implements ITodoItem {
    private String title; private String content;

    @Override
    public String getTitle() ...

    public String setTitle(..) ...
}
</code>```

I wonder now what is the more common, smarter etc. option (or are there more?) and what are the arguments?

Alternative 1) for my feeling depends to much on the fact, that the items have to be in the same package making it to difficult to expand the program.

Alternative 2) looks odd to me, because all tiny objects would now become an interface with the getter methods. I am using it and technically I am satisfied (as it prevents me from accidantally changing an object). However, it is not immutable, as the object may be cast back to ToDo-Item and then the original is changed. So this is not good for public apis. Do I really have to clone every object if I want immutability?

Alternative 3) gets messy quick because one controller would then contain all the getters of the tiny objects. This does not comply to "let the object do the work".

What are your experiences and thoughts on this?

答:
What about designing your "basic objects" as 100% immutable objects?

```<code>public final class TodoItem {
    final private String title;
    final private String content;

    public TodoItem (String title, String content) {
        this.title= title;
        this.content = content;
     }

    public String getTitle() ...
    // no setter at all, title and content can only set when creating a new object
}
</code>```

Implement your program in terms of such objects, then you can pass them around between arbitrary layers, without the risk of getting unwanted side effects. Here you find a more detailed example.

Body:
What about designing your "basic objects" as 100% immutable objects?

public final class TodoItem {
    final private String title;
    final private String content;

    public TodoItem (String title, String content) {
        this.title= title;
        this.content = content;
     }

    public String getTitle() ...
    // no setter at all, title and content can only set when creating a new object
}

Implement your program in terms of such objects, then you can pass them around between arbitrary layers, without the risk of getting unwanted side effects. Here you find a more detailed example.


问:
Library design: better to leave potentially destructive feature in with a warning, or cut it out completely?
I recently created a red-black tree in C# to better understand how it works. With it, I implemented an in-order enumerator, however I quickly realized that enumerating a tree can have destructive results.

Consider this code:

```<code>RedBlackTree<Person> tree = new RedBlackTree<Person>();
tree.Add(new Person("Randy"));
// add more people
...

foreach(var person in tree)
{
    if (person.Name == "Randy")
    {
        person.Name = "Cheeseburger eater";
    }
}
</code>```

The tree requires the generic parameter to implement IComparable interface, in order to correctly determine ordering of items.

If Person class is compared  by name, then, by changing the name during enumeration, we might have broken the ordering. e.g. randyNode.CompareTo(randyNode.Right) < 0 might be false, which breaks the fundamental BST property, that left child is smaller than its parent and right child bigger.

In this case, is it better to remove tree enumeration altogether, or should I keep it in, with a huge warning to not modify the items during enumeration?

答:
You'll find with existing C# collections, attempting to mutate the collection while iterating causes exceptions. It would be idiomatic to throw an exception in that scenario in your collection.

The problem that you'll face is that this doesn't matter if you're iterating. If someone changes person.Name, your RBT is already out of order - iteration or no.


答:
It depends on whether any users (including yourself) will use the enumerator feature of the library. If there are use cases where it would make the job better, or easier, it will be nice to have. Many enumerator libraries, including .NET, have requirements that the underlying set not change during enumeration.

If, on the other hand, the feature is not used much, and only leads to frustration, then take it out. If it's useful to you internally as the implementor of the library, then hide it from public use. You know the ins and outs of its use and will not shoot yourself in the foot with it (hopefully).

Title: Library design: better to leave potentially destructive feature in with a warning, or cut it out completely?

Body:
I recently created a red-black tree in C# to better understand how it works. With it, I implemented an in-order enumerator, however I quickly realized that enumerating a tree can have destructive results.

Consider this code:

```<code>RedBlackTree<Person> tree = new RedBlackTree<Person>();
tree.Add(new Person("Randy"));
// add more people
...

foreach(var person in tree)
{
    if (person.Name == "Randy")
    {
        person.Name = "Cheeseburger eater";
    }
}
</code>```

The tree requires the generic parameter to implement IComparable interface, in order to correctly determine ordering of items.

If Person class is compared  by name, then, by changing the name during enumeration, we might have broken the ordering. e.g. randyNode.CompareTo(randyNode.Right) < 0 might be false, which breaks the fundamental BST property, that left child is smaller than its parent and right child bigger.

In this case, is it better to remove tree enumeration altogether, or should I keep it in, with a huge warning to not modify the items during enumeration?


问:
Best Way To Store Images For Mobile Synchronization
The scenario is, I have a Web Dashboard (Developed using PHP + MySQL) and have Android and iOS Apps synchronizing data from the Web Dashboard (only one way i.e. Dashboard to Mobile Apps)

Now the problem is that, on few screens in App I need to show images which will be captured in Web Dashboard via file upload.

Firstly, I designed the tables such that to store the image paths. But in that way both the App's needs to run a background service of something to fetch the images from those URL's once they get the Table data in JSON Format.

Later, I changed the DB Design to store Image BLOB, which made this job simpler, but while synchronizing, if I have around 100 Rows with Image BLOB's, it's taking a lot of time to Sync. The number of rows is going to increase further.

And for the first time, when the App's are installed I'm supposed to Sync all the data at once then on interval only incremented transactional data.

So the main problem is with First time data.

Any suggestions on how can I provide a better solution?

答:
I would only sync the URLs to the images stored on the server, not the complete image as BLOB. So the sync is fast and the images must be loaded 'on time' when they are used/displayed.

Edit: I saw, that your first solution was something like that. So sorry, no news for you, but I still think lazy image loading should solve the problem...


问:
Bad sign if nobody can comprehend one's code?
If a coder writes code that nobody other than he can understand, and code reviews always end with the reviewer scratching his head or holding their head in their hands, is this a clear sign that the coder is simply not cut-out for professional programming?  Would this be enough to warrant a career change?  How important is comprehensible code in this industry?

Consider these C examples, compare:

```<code>if (b)
  return 42;
else
  return 7;
</code>```

versus:

```<code>return (b * 42) | (~(b - 1) * 7);
</code>```

Is there ever an excuse to employ the latter example? if so, when and why?

EDIT: Leaving the original latter snippet for consideration, adding a correction:

```<code>return (b * 42) | ((b - 1) & 7);
</code>```

I think the other interesting observation is that it requires that b is 1 for true and 0 for false, any other values would render strange results.

答:
Replacing if-s with arithmetic/logic expression is sometimes necessary where long processor piping is required. That makes the code to always run the same instructions whatever the condition, making it more suitable for parallelization.

That said, the provided sample is wrong, since the two samples are not equivalent:

```<code>if (b)
  return 42;
else
  return 7;
</code>```

can be return ((b&1)*42)|((1-(b&1)))*7

The programmer of the OP sample may have done a wrong if-elimination, or the OP itself may have misinterpreted the programmer intentions when guessing the if traditional switch in a wrong way. Saying which of the two is correct is hard not knowing what the requirement was.

Note that the expression is not so that "obscure": it' just a linear combination in the form P*(t)+Q*(1-t) (with t=0..1) every programmer should be aware of, since it is the base of most of linear algebra.

The only thing I can understand is that between the coder and the reviewer there is a different cultural base about parallel processing and linear algebra. This IMHO, doesn't make one superior to the other, if correctness is proven.

Body:
Replacing if-s with arithmetic/logic expression is sometimes necessary where long processor piping is required. That makes the code to always run the same instructions whatever the condition, making it more suitable for parallelization.

That said, the provided sample is wrong, since the two samples are not equivalent:

if (b)
  return 42;
else
  return 7;

can be return ((b&1)*42)|((1-(b&1)))*7

The programmer of the OP sample may have done a wrong if-elimination, or the OP itself may have misinterpreted the programmer intentions when guessing the if traditional switch in a wrong way. Saying which of the two is correct is hard not knowing what the requirement was.

Note that the expression is not so that "obscure": it' just a linear combination in the form P*(t)+Q*(1-t) (with t=0..1) every programmer should be aware of, since it is the base of most of linear algebra.

The only thing I can understand is that between the coder and the reviewer there is a different cultural base about parallel processing and linear algebra. This IMHO, doesn't make one superior to the other, if correctness is proven.


答:
To make it short:

The first sentence of amon's answer is important.

But your guess is correct, too:
1000^2 is 4 times more than (2*1000)^2. I.e. if 1000^2 are equal to 10 seconds on a given hardware, then (2*1000)^2 are equal to 40 seconds. It's simply the rule of three.

One more note: If you are dealing with the running time of the implementation of an algorithm, you should also test the performance of your implementation. Simple programming "mistakes" can make a huge difference in real world.

Title: Estimating run time of algorithm

Body:
For instance if i have an algorithm that is O(n2) and it will run for 10 seconds for a problem size of 1000. Now if i were to double the problem size to 2000 i want to know the approximate run time in seconds. I know the answer for it but i want to understand the logic on how to get to the answer. So here is what i am thinking.

```<code>N = 1000 , Therefore 1000^2 = 10 seconds
N = 2000,  Therefore (2*1000)^2, // stuck here
</code>```

Now i am not sure i mean i know it will be 40 seconds because 2 to the power of 2 is 4 and then you multiply the 10 seconds by 4 and get 40 seconds but not entirely sure if this is right thinking. Was wondering if someone can break it down in simple terms?


答:
On file size

You need to deal with the vast array of issues that come from the sheer size of images - whether compressed or not, images range from hundreds of KBs and up - which is tens to hundreds times larger than the typical amount of data your frontend/backend handles per operation.

Therefore, the first strategy is to focus on reducing the image size. Don't bother with techniques that only improve a few percents - to make things improve, you need an order of magnitude better compression.

The best file-size-reduction approach is to scale down the image - as much as you can without making your users angry.

If you use JPEG or WebP (or some other lossy formats) you can try use different quality level. Sometimes the best trade-off is obtained from a combination of scaling down and adjusting quality level. Don't limit your scale-down factors to powers-of-two.

The second best image compression approach depends on the type of image content. You will need to learn about the basics of compressed image formats, and be creative applying those basics.

In one very simple approach, large areas of uniform color is simply cropped away from the image, and replaced with a background color - to be painted by the app - using the same RGB hex.

On versioning

The backend database needs to be able to serve a checksum, timestamp (last modified time) or file version number that serves to inform the app whether they have the most up-to-date file.

On keeping the user from boredom

You might need to show small, fast-to-download thumbnails (which are scaled down versions of the image) just in case your app users are quick-tempered. Make sure these thumbnails are properly cached by the backend - loading the thumbnails from disk adds to the latency, which defeats the purpose.

On backend image processing

It looks like the prevailing advice on Programmers.StackExchange is to keep a queue of image processing operations to be performed; the queue to be executed by an out-of-process ImageMagick worker process; results are added back to another "finished queue" to be handled by the backend.

Title: Best Way To Store Images For Mobile Synchronization

Body:
The scenario is, I have a Web Dashboard (Developed using PHP + MySQL) and have Android and iOS Apps synchronizing data from the Web Dashboard (only one way i.e. Dashboard to Mobile Apps)

Now the problem is that, on few screens in App I need to show images which will be captured in Web Dashboard via file upload.

Firstly, I designed the tables such that to store the image paths. But in that way both the App's needs to run a background service of something to fetch the images from those URL's once they get the Table data in JSON Format.

Later, I changed the DB Design to store Image BLOB, which made this job simpler, but while synchronizing, if I have around 100 Rows with Image BLOB's, it's taking a lot of time to Sync. The number of rows is going to increase further.

And for the first time, when the App's are installed I'm supposed to Sync all the data at once then on interval only incremented transactional data.

So the main problem is with First time data.

Any suggestions on how can I provide a better solution?


问:
raw, weak_ptr, unique_ptr, shared_ptr etc... How to choose them wisely?
There is a lot of pointers in C++ but to be honest in 5 years or so in C++ programming (specifically with the Qt Framework) I only use the old raw pointer:

```<code>SomeKindOfObject *someKindOfObject = new SomeKindOfObject();
</code>```

I know there are a lot of other "smart" pointers:

```<code>// shared pointer:
shared_ptr<SomeKindofObject> Object;

// unique pointer:
unique_ptr<SomeKindofObject> Object;

// weak pointer:
weak_ptr<SomeKindofObject> Object;
</code>```

But I don't have the slightest idea of what to do with them and what they can offer me in comparison of raw pointers.

For example I have this class header:

```<code>#ifndef LIBRARY
#define LIBRARY

class LIBRARY
{
public:
    // Permanent list that will be updated from time to time where
    // each items can be modified everywhere in the code:
    QList<ItemThatWillBeUsedEveryWhere*> listOfUselessThings;
private:
    // Temporary reader that will read something to put in the list
    // and be quickly deleted:
    QSettings *_reader;
    // A dialog that will show something (just for the sake of example):
    QDialog *_dialog;
};

#endif
</code>```

This is clearly not exhaustive but for each of these 3 pointers is it OK to leave them "raw" or should I use something more appropriate?

And in the second time, if an employer will read the code, will he be strict on what kind of pointers I use or not?

答:
A "raw" pointer is unmanaged. That is, the following line:

```<code>SomeKindOfObject *someKindOfObject = new SomeKindOfObject();
</code>```

... will leak memory if an accompanying delete is not executed at the proper time.

auto_ptr

In order to minimize these cases, std::auto_ptr<> was introduced. Due to the limitations of C++ prior to the 2011 standard, however, it's still very easy for auto_ptr to leak memory. It is sufficient for limited cases, such as this, however:

```<code>void func() {
    std::auto_ptr<SomeKindOfObject> sKOO_ptr(new SomeKindOfObject());
    // do some work
    // will not leak if you do not copy sKOO_ptr.
}
</code>```

One of its weakest use-cases is in containers. This is because if a copy of an auto_ptr<> is made and the old copy is not carefully reset, then the container may delete the pointer and lose data.

unique_ptr

As a replacement, C++11 introduced std::unique_ptr<>:

```<code>void func2() {
    std::unique_ptr<SomeKindofObject> sKOO_unique(new SomeKindOfObject());

    func3(sKOO_unique); // now func3() owns the pointer and sKOO_unique is no longer valid
}
</code>```

Such a unique_ptr<> will be correctly cleaned up, even when it's passed between functions. It does this by semantically representing "ownership" of the pointer - the "owner" cleans it up. This makes it ideal for use in containers:

```<code>std::vector<std::unique_ptr<SomeKindofObject>> sKOO_vector();
</code>```

Unlike auto_ptr<>, unique_ptr<> is well-behaved here, and when the vector resizes, none of the objects will be accidentally deleted while the vector copies its backing store.

shared_ptr and weak_ptr

unique_ptr<> is useful, to be sure, but there are cases where you want two parts of your code base to be able to refer to the same object and copy the pointer around, while still being guaranteed proper cleanup. For example, a tree might look like this, when using std::shared_ptr<>:

```<code>template<class T>
struct Node {
    T value;
    std::shared_ptr<Node<T>> left;
    std::shared_ptr<Node<T>> right;
};
</code>```

In this case, we can even hold on to multiple copies of a root node, and the tree will be properly cleaned up when all copies of the root node are destroyed.

This works because each shared_ptr<> holds on to not only the pointer to the object, but also a reference count of all of the shared_ptr<> objects that refer to the same pointer. When a new one is created, the count goes up. When one is destroyed, the count goes down. When the count reaches zero, the pointer is deleted.

So this introduces a problem: Double-linked structures end up with circular references. Say we want to add a parent pointer to our tree Node:

```<code>template<class T>
struct Node {
    T value;
    std::shared_ptr<Node<T>> parent;
    std::shared_ptr<Node<T>> left;
    std::shared_ptr<Node<T>> right;
};
</code>```

Now, if we remove a Node, there's a cyclic reference to it. It'll never be deleted because its reference count will never be zero.

To solve this problem, you use a std::weak_ptr<>:

```<code>template<class T>
struct Node {
    T value;
    std::weak_ptr<Node<T>> parent;
    std::shared_ptr<Node<T>> left;
    std::shared_ptr<Node<T>> right;
};
</code>```

Now, things will work correctly, and removing a node will not leave stuck references to the parent node. It makes walking the tree a little more complicated, however:

```<code>std::shared_ptr<Node<T>> parent_of_this = node->parent.lock();
</code>```

This way, you can lock a reference to the node, and you have a reasonable guarantee it won't disappear while you're working on it, since you're holding on to a shared_ptr<> of it.

make_shared and make_unique

Now, there are some minor problems with shared_ptr<> and unique_ptr<> that should be addressed. The following two lines have a problem:

```<code>foo_unique(std::unique_ptr<SomeKindofObject>(new SomeKindOfObject()), thrower());
foo_shared(std::shared_ptr<SomeKindofObject>(new SomeKindOfObject()), thrower());
</code>```

If thrower() throws an exception, both lines will leak memory. And more than that, shared_ptr<> holds the reference count far away from the object it points to and this can mean a second allocation). That's not usually desirable.

C++11 provides std::make_shared<>() and C++14 provides std::make_unique<>() to solve this problem:

```<code>foo_unique(std::make_unique<SomeKindofObject>(), thrower());
foo_shared(std::make_shared<SomeKindofObject>(), thrower());
</code>```

Now, in both cases, even if thrower() throws an exception, there will not be a leak of memory. As a bonus, make_shared<>() has the opportunity to create its reference count in the same memory space as its managed object, which can both be faster and can save a few bytes of memory, while giving you an exception safety guarantee!

Notes about Qt

It should be noted, however, that Qt, which must support pre-C++11 compilers, has its own garbage-collection model: Many QObjects have a mechanism where they will be destroyed properly without the need for the user to delete them.

I do not know how QObjects will behave when managed by C++11 managed pointers, so I can not say that shared_ptr<QDialog> is a good idea. I do not have enough experience with Qt to say for sure, but I believe that Qt5 has been adjusted for this use case.

Body:
A "raw" pointer is unmanaged. That is, the following line:

SomeKindOfObject *someKindOfObject = new SomeKindOfObject();

... will leak memory if an accompanying delete is not executed at the proper time.

auto_ptr

In order to minimize these cases, std::auto_ptr<> was introduced. Due to the limitations of C++ prior to the 2011 standard, however, it's still very easy for auto_ptr to leak memory. It is sufficient for limited cases, such as this, however:

void func() {
    std::auto_ptr<SomeKindOfObject> sKOO_ptr(new SomeKindOfObject());
    // do some work
    // will not leak if you do not copy sKOO_ptr.
}

One of its weakest use-cases is in containers. This is because if a copy of an auto_ptr<> is made and the old copy is not carefully reset, then the container may delete the pointer and lose data.

unique_ptr

As a replacement, C++11 introduced std::unique_ptr<>:

void func2() {
    std::unique_ptr<SomeKindofObject> sKOO_unique(new SomeKindOfObject());

    func3(sKOO_unique); // now func3() owns the pointer and sKOO_unique is no longer valid
}

Such a unique_ptr<> will be correctly cleaned up, even when it's passed between functions. It does this by semantically representing "ownership" of the pointer - the "owner" cleans it up. This makes it ideal for use in containers:

std::vector<std::unique_ptr<SomeKindofObject>> sKOO_vector();

Unlike auto_ptr<>, unique_ptr<> is well-behaved here, and when the vector resizes, none of the objects will be accidentally deleted while the vector copies its backing store.

shared_ptr and weak_ptr

unique_ptr<> is useful, to be sure, but there are cases where you want two parts of your code base to be able to refer to the same object and copy the pointer around, while still being guaranteed proper cleanup. For example, a tree might look like this, when using std::shared_ptr<>:

template<class T>
struct Node {
    T value;
    std::shared_ptr<Node<T>> left;
    std::shared_ptr<Node<T>> right;
};

In this case, we can even hold on to multiple copies of a root node, and the tree will be properly cleaned up when all copies of the root node are destroyed.

This works because each shared_ptr<> holds on to not only the pointer to the object, but also a reference count of all of the shared_ptr<> objects that refer to the same pointer. When a new one is created, the count goes up. When one is destroyed, the count goes down. When the count reaches zero, the pointer is deleted.

So this introduces a problem: Double-linked structures end up with circular references. Say we want to add a parent pointer to our tree Node:

template<class T>
struct Node {
    T value;
    std::shared_ptr<Node<T>> parent;
    std::shared_ptr<Node<T>> left;
    std::shared_ptr<Node<T>> right;
};

Now, if we remove a Node, there's a cyclic reference to it. It'll never be deleted because its reference count will never be zero.

To solve this problem, you use a std::weak_ptr<>:

template<class T>
struct Node {
    T value;
    std::weak_ptr<Node<T>> parent;
    std::shared_ptr<Node<T>> left;
    std::shared_ptr<Node<T>> right;
};

Now, things will work correctly, and removing a node will not leave stuck references to the parent node. It makes walking the tree a little more complicated, however:

std::shared_ptr<Node<T>> parent_of_this = node->parent.lock();

This way, you can lock a reference to the node, and you have a reasonable guarantee it won't disappear while you're working on it, since you're holding on to a shared_ptr<> of it.

make_shared and make_unique

Now, there are some minor problems with shared_ptr<> and unique_ptr<> that should be addressed. The following two lines have a problem:

foo_unique(std::unique_ptr<SomeKindofObject>(new SomeKindOfObject()), thrower());
foo_shared(std::shared_ptr<SomeKindofObject>(new SomeKindOfObject()), thrower());

If thrower() throws an exception, both lines will leak memory. And more than that, shared_ptr<> holds the reference count far away from the object it points to and this can mean a second allocation). That's not usually desirable.

C++11 provides std::make_shared<>() and C++14 provides std::make_unique<>() to solve this problem:

foo_unique(std::make_unique<SomeKindofObject>(), thrower());
foo_shared(std::make_shared<SomeKindofObject>(), thrower());

Now, in both cases, even if thrower() throws an exception, there will not be a leak of memory. As a bonus, make_shared<>() has the opportunity to create its reference count in the same memory space as its managed object, which can both be faster and can save a few bytes of memory, while giving you an exception safety guarantee!

Notes about Qt

It should be noted, however, that Qt, which must support pre-C++11 compilers, has its own garbage-collection model: Many QObjects have a mechanism where they will be destroyed properly without the need for the user to delete them.

I do not know how QObjects will behave when managed by C++11 managed pointers, so I can not say that shared_ptr<QDialog> is a good idea. I do not have enough experience with Qt to say for sure, but I believe that Qt5 has been adjusted for this use case.


问:
Protect memory from a potentially seg faulting function call
How can one safely call a function that might segfault without corrupting the stack or the heap?

These SO questions cover using signal handlers and setjmp.h to regain control.

Coming back to life after Segmentation Violation

Best practices for recovering from a segmentation fault

They neglect the likely memory corruption that occurs prior to a seg fault.

What strategies can be used to isolate the memory space of a function and its caller?

This is just a curiosity question, there's no specific problem I'm trying to solve. Let's just suppose we're programming something that absolutely cannot crash -- pacemaker, Mars orbiter, nuclear launch control, take your pick. We've already thoroughly unit tested all our code and formally proven its correctness. For bureaucratic reasons we have to use C++ and Linux.

I was trying to sketch this out with clone(). My idea was to run the function with as much isolation as possible and pass data back and forth by squirreling it away at the bottom of the child's stack.

Is that reasonable or is there a better way to do this?

答:
Short answer: Absolutely no guarantees can be made about a program that crashes (or in fact one that DOESN'T crash). If an application crashes, the entire program's data (and any other writable memory areas, files, databases, etc that this program MAY have touched) areas must be treated as "probably not correct".

Long answer: Since there is absolutely no telling what happens in code that doesn't "behave correctly", you can't actually know that data has not been clobbered BEFORE the segfault (or stackfault, bus error, divide by zero, overflow, etc).

I had a bug many years ago, on a system that didn't have memory protection enabled, which was caused by swapping the order of values in memset (due to calling convention mixup and not including the correct headers and memset having a non-standard calling convention in that particular compiler), which meant that instead of memset(dest, fill, size), the code was doing memset(size, fill, dest) - given that memory addresses are generally MUCH higher than the size of the thing than you want to memset, the result was that the entire memory from somewhere near zero to the point in the code which was executing memset got filled with the value fill. Debugging that wasn't easy even with an In-Circuit emulator that would tell me exactly what my last N instructions where (N being a large number like 16K or 64K) - not really helpful when the memory I executed in has been overwritten (sometimes it would actually then continue executing garbage instructions for quite some time before it become something REALLY bad and actually stopped). Of course, if this happens only at the time of 14.52.15 on Thursdays where the day is divisible by three and seven, in months that have an R in their English name and only with outside temperatures between 18 and 21 degrees centigrade, you may be spending some time figuring out why the system crashed.

Now, you can have similar scenarios in code that uses memcpy or memset with just simple math errors in the calculation of the size (e.g. subtracting a larger value from a smaller value and ending up with "negative" size - since sizes are typically unsigned, that ends up being a HUGE value. Then segfaults when it reaches the "end" of some memory-region (data, heap, stack, or whatever it may be). There is REALLY no way to guard against this sort of overwrite.

Running suspect code in a separate process, and, assuming it didn't crash, check the output from that process before accepting it. But of course, I can write a program to calculate pi with many decimals, that doesn't crash, but because I've made some mistake in it (e.g. copied the wrong formula from Wikipedias article about calculation series for famous numbers), it comes up with 2.71828182845904523536028747135266249775724709369995957496696762772407663 rather than 3.1415926... Without KNOWING what the result should be, you can't really know whether it is right or not. And of course, if you already know the result, you don't need to do anything to figure out what the answer should be.

Systems designed for high security typically have extra code to safe-guard that the result is correct - one typical approach is to have multiple teams, designing their own software and hardware, and then have a "mediator" in that collects all the "results" from each system - if they all match, good. If they don't do, raise an alarm something to indicate that something is now right. If the result of one system is "crash", then restart that system (and raise the alarm). Since the systems are designed by different teams, one hopes that any bugs are UNIQUE to each system. Add to this VERY THOROUGH testing, lots of review by people who didn't write the code, but are professionals specializedon spotting "bad" things in code.

The number of systems and the action when something goes wrong depends on the situation. In a train, you may get away with two systems and a mediator - the mediator just pulls the emergency brake when results differ and waits for the traindriver to push some buttons to reset the train computers. In an aeroplane, there is no such thing as an emergency brake, so a "majority vote" system is used to determine what is the best action (and big red flashing light saying "computer systems don't agree") - probably a good idea to go to "manual" rather than "autopilot" at that point too.

In cases of medical software (related to equipment that is directly connected to patients, not the database keeping the patient records, or the computer that people log into their favourite website on when they visit the hospital library), you also have to have medical software certification, which includes using an OS with medical certification, and code-review of the specific software by an external body whose whole purpose as an organisation is to ensure the safety of medical equipment. So a pacemaker would certainly fall into this category.

Of course, no amount of reviews, testing and so on will 100% stop safety-critical systems from giving bad results. I believe the airliner crashing a few years back on a flight from Brazil to Europe was partly down to the planes computer system giving back incorrect values, and the "mediator" was happy with that (the pilots were also making mistakes, but this was at least in part caused by being given the wrong information in the first place) - I don't believe the computers crashed, they just gave readings that were incorrect in relation to reality.


答: Another point to consider is that, depending on the size of your project, what version of Java will be out and what will be obsolete.  For most sizable projects, it would be wise to work with the current 'out of beta/alpha' version, (in this case Java 8) which may or may not be current when you release.</p>


答:
This question is indeed too broad to be answered by a single answer on any single StackExchange site.

You might want to visit the Information Security site to read about the practical techniques that you will want to adopt for your software. Of course, you can probably find similar techniques discussed on this site or at StackOverflow, written from a programmer's perspective.

However - don't cross-post your question there; it is too broad and the information you provided aren't pinpointing enough for anyone to give a concise answer.

There is already a large collection of literature on:

Software fault isolation

Software verification

Trustworthy computing

Virtualization

Sandboxing

etc.

There is also an adage to be remembered at all times: #NoSilverBullet

Given your description and your initial comments, I believe the best fit for your (hypothetical?) situation is to use Cleanroom Engineering. In other words, the condition under which code is designed and developed needs to be carefully controlled. Code that is developed outside this environment is not allowed to be introduced. Throw away your crash-causing code the first time it happens. Period. (Okay, maybe give it a three-strikes.)

It stems from the observation that it is not always possible to fix-up buggy source code, especially if that buggy source code doesn't have a clean design (or any design at all) that can be formally verified.

Formal verification is not easy to apply for arbitrary pieces of source code. To use formal verification, it is encouraged to write source code with verification in mind - often writing code in a different style than a typical programmer would.

Your hypothetical situation actually mentions three separate failure modes:

The code produces wrong results, either due to algorithm bugs, or corruption of algorithm's own data structures (but not outside).

The code corrupts some other module's data structures; as a result, its result might either be correct or wrong, but the resulting corruption would cause silent data loss, failure in an separate (possibly unrelated) module, or a crash at any time in the future.

The code causes a crash. The program stops executing (because there is no logical way to continue.)

The software fault isolation used by Google Portable Native Client (both versions) are interesting:

 *

Title: Protect memory from a potentially seg faulting function call

Body:
How can one safely call a function that might segfault without corrupting the stack or the heap?

These SO questions cover using signal handlers and setjmp.h to regain control.

Coming back to life after Segmentation Violation

Best practices for recovering from a segmentation fault

They neglect the likely memory corruption that occurs prior to a seg fault.

What strategies can be used to isolate the memory space of a function and its caller?

This is just a curiosity question, there's no specific problem I'm trying to solve. Let's just suppose we're programming something that absolutely cannot crash -- pacemaker, Mars orbiter, nuclear launch control, take your pick. We've already thoroughly unit tested all our code and formally proven its correctness. For bureaucratic reasons we have to use C++ and Linux.

I was trying to sketch this out with clone(). My idea was to run the function with as much isolation as possible and pass data back and forth by squirreling it away at the bottom of the child's stack.

Is that reasonable or is there a better way to do this?


问:
Single method with many parameters vs many methods that must be called in order
I have some raw data I need to do many things to (shift it, rotate it, scale it along certain axis, rotate it to a final position) and I am not sure what the best way to do this to maintain code readability. On one hand, I can make a single method with many parameters (10+) to do what I need, but this is a code reading nightmare. On the other hand, I could make multiple methods with 1-3 parameters each, but these methods would need to be called in a very specific order to get the correct result. I have read that it is best for methods to do one thing and do it well, but it seems like having many methods that need to be called in order opens up code for hard-to-find bugs.

Is there a programming paradigm I could use that would minimize bugs and make code easier to read?

答:
The "must be executed in order" argument is moot since pretty much all of your code must be executed in the correct order. After all, you can't write to a file, then open it then close it, can you?

You should concentrate on what makes your code the most maintainable. This will usually mean writing functions that are small and easily understood. Each function should have a single purpose and not have side effects that are unanticipated.


答:
Beware of temporal coupling. However, this is not always an issue.

If you must perform steps in order, it follows that step 1 produces some object required for step 2 (e.g. a file stream or other data structure). This alone requires that the second function must be called after the first, it is not even possible to call them in the wrong order accidentally.

By splitting your functionality up into bite-sized pieces, each part is easier to understand, and definitely easier to test in isolation. If you have a huge 100 line function and something in the middle breaks, how does your failed test tell you what is wrong? If one of your five line methods breaks, your failed unit test directs you immediately toward the one piece of code that needs attention.

This is how complex code should look:

```<code>public List<Widget> process(File file) throws IOException {
  try (BufferedReader in = new BufferedReader(new FileReader(file))) {
    List<Widget> widgets = new LinkedList<>();
    String line;
    while ((line = in.readLine()) != null) {
      if (isApplicable(line)) { // Filter blank lines, comments, etc.
        Ore o = preprocess(line);
        Ingot i = smelt(o);
        Alloy a = combine(i, new Nonmetal('C'));
        Widget w = smith(a);
        widgets.add(w);
      }
    }
    return widgets;
  }
}
</code>```

At any point during the process of converting raw data into a finished widget, each function returns something required by the next step in the process. One cannot form an alloy from slag, one must smelt (purify) it first. One may not create a widget without the proper allow (e.g. steel) as input.

The specific details of each step are contained in individual functions that can be tested: rather than unit testing the entire process of mining rocks and creating widgets, test each specific step. Now you have an easy way of ensuring that if your "create widget" process fails, you can narrow down the specific reason.

Aside from the benefits of testing and proving correctness, writing code this way is far easier to read. Nobody can understand a huge parameter list. Break it down into small pieces, and show what each little piece means: that is grokkable.

Title: Single method with many parameters vs many methods that must be called in order

Body:
I have some raw data I need to do many things to (shift it, rotate it, scale it along certain axis, rotate it to a final position) and I am not sure what the best way to do this to maintain code readability. On one hand, I can make a single method with many parameters (10+) to do what I need, but this is a code reading nightmare. On the other hand, I could make multiple methods with 1-3 parameters each, but these methods would need to be called in a very specific order to get the correct result. I have read that it is best for methods to do one thing and do it well, but it seems like having many methods that need to be called in order opens up code for hard-to-find bugs.

Is there a programming paradigm I could use that would minimize bugs and make code easier to read?

Body:
Beware of temporal coupling. However, this is not always an issue.

If you must perform steps in order, it follows that step 1 produces some object required for step 2 (e.g. a file stream or other data structure). This alone requires that the second function must be called after the first, it is not even possible to call them in the wrong order accidentally.

By splitting your functionality up into bite-sized pieces, each part is easier to understand, and definitely easier to test in isolation. If you have a huge 100 line function and something in the middle breaks, how does your failed test tell you what is wrong? If one of your five line methods breaks, your failed unit test directs you immediately toward the one piece of code that needs attention.

This is how complex code should look:

public List<Widget> process(File file) throws IOException {
  try (BufferedReader in = new BufferedReader(new FileReader(file))) {
    List<Widget> widgets = new LinkedList<>();
    String line;
    while ((line = in.readLine()) != null) {
      if (isApplicable(line)) { // Filter blank lines, comments, etc.
        Ore o = preprocess(line);
        Ingot i = smelt(o);
        Alloy a = combine(i, new Nonmetal('C'));
        Widget w = smith(a);
        widgets.add(w);
      }
    }
    return widgets;
  }
}

At any point during the process of converting raw data into a finished widget, each function returns something required by the next step in the process. One cannot form an alloy from slag, one must smelt (purify) it first. One may not create a widget without the proper allow (e.g. steel) as input.

The specific details of each step are contained in individual functions that can be tested: rather than unit testing the entire process of mining rocks and creating widgets, test each specific step. Now you have an easy way of ensuring that if your "create widget" process fails, you can narrow down the specific reason.

Aside from the benefits of testing and proving correctness, writing code this way is far easier to read. Nobody can understand a huge parameter list. Break it down into small pieces, and show what each little piece means: that is grokkable.


答:
I would create an »ImageProcesssor« (or whatever name suits your project) and a configuration object ProcessConfiguration, which holds all necessary parameters.

```<code> ImageProcessor p = new ImageProcessor();

 ProcessConfiguration config = new processConfiguration().setTranslateX(100)
                                                         .setTranslateY(100)
                                                         .setRotationAngle(45);
 p.process(image, config);
</code>```

Inside the imageprocessor you encapsulate the whole process behind one mehtod process()

```<code>public class ImageProcessor {

    public Image process(Image i, ProcessConfiguration c){
        Image processedImage=i.getCopy();
        shift(processedImage, c);
        rotate(processedImage, c);
        return processedImage;
    }

    private void rotate(Image i, ProcessConfiguration c) {
        //rotate
    }

    private void shift(Image i, ProcessConfiguration c) {
        //shift
    }
}
</code>```

This method calls the transformational methods in the correct order shift(), rotate().
Each method gets appropriate parameters from the passed ProcessConfiguration.

```<code>public class ProcessConfiguration {

    private int translateX;

    private int rotationAngle;

    public int getRotationAngle() {
        return rotationAngle;
    }

    public ProcessConfiguration setRotationAngle(int rotationAngle){
        this.rotationAngle=rotationAngle;
        return this;
    }

    public int getTranslateY() {
        return translateY;
    }

    public ProcessConfiguration setTranslateY(int translateY) {
        this.translateY = translateY;
        return this;
    }

    public int getTranslateX() {
        return translateX;
    }

    public ProcessConfiguration setTranslateX(int translateX) {
        this.translateX = translateX;
        return this;
    }

    private int translateY;

}
</code>```

I used fluid interfaces

```<code>public ProcessConfiguration setRotationAngle(int rotationAngle){
    this.rotationAngle=rotationAngle;
    return this;
}
</code>```

which allows nifty initialization (as seen above).

The obvious advantage, encapsulating necessary parameters in one object.
Your method signatures become readable:

private void shift(Image i, ProcessConfiguration c)

It is about shifting an image and detailed parameters are somehow configured.

Alternatively, you could create a ProcessingPipeline:

```<code>public class ProcessingPipeLine {

    Image i;

    public ProcessingPipeLine(Image i){
        this.i=i;
    };

    public ProcessingPipeLine shift(Coordinates c){
        shiftImage(c);
        return this;
    }

    public ProcessingPipeLine rotate(int a){
        rotateImage(a);
        return this;
    }

    public Image getResultingImage(){
        return i;
    }

    private void rotateImage(int angle) {
        //shift
    }

    private void shiftImage(Coordinates c) {
        //shift
    }

}
</code>```

A method call to a method processImage would instantiate such a pipeline and make transparent what and in which order is done: shift, rotate

```<code>public Image processImage(Image i, ProcessConfiguration c){
    Image processedImage=i.getCopy();
    processedImage=new ProcessingPipeLine(processedImage)
            .shift(c.getCoordinates())
            .rotate(c.getRotationAngle())
            .getResultingImage();
    return processedImage;
}
</code>```

Body:
I would create an »ImageProcesssor« (or whatever name suits your project) and a configuration object ProcessConfiguration, which holds all necessary parameters.

 ImageProcessor p = new ImageProcessor();

 ProcessConfiguration config = new processConfiguration().setTranslateX(100)
                                                         .setTranslateY(100)
                                                         .setRotationAngle(45);
 p.process(image, config);

Inside the imageprocessor you encapsulate the whole process behind one mehtod process()

public class ImageProcessor {

    public Image process(Image i, ProcessConfiguration c){
        Image processedImage=i.getCopy();
        shift(processedImage, c);
        rotate(processedImage, c);
        return processedImage;
    }

    private void rotate(Image i, ProcessConfiguration c) {
        //rotate
    }

    private void shift(Image i, ProcessConfiguration c) {
        //shift
    }
}

This method calls the transformational methods in the correct order shift(), rotate().
Each method gets appropriate parameters from the passed ProcessConfiguration.

public class ProcessConfiguration {

    private int translateX;

    private int rotationAngle;

    public int getRotationAngle() {
        return rotationAngle;
    }

    public ProcessConfiguration setRotationAngle(int rotationAngle){
        this.rotationAngle=rotationAngle;
        return this;
    }

    public int getTranslateY() {
        return translateY;
    }

    public ProcessConfiguration setTranslateY(int translateY) {
        this.translateY = translateY;
        return this;
    }

    public int getTranslateX() {
        return translateX;
    }

    public ProcessConfiguration setTranslateX(int translateX) {
        this.translateX = translateX;
        return this;
    }

    private int translateY;

}

I used fluid interfaces

public ProcessConfiguration setRotationAngle(int rotationAngle){
    this.rotationAngle=rotationAngle;
    return this;
}

which allows nifty initialization (as seen above).

The obvious advantage, encapsulating necessary parameters in one object.
Your method signatures become readable:

private void shift(Image i, ProcessConfiguration c)

It is about shifting an image and detailed parameters are somehow configured.

Alternatively, you could create a ProcessingPipeline:

public class ProcessingPipeLine {

    Image i;

    public ProcessingPipeLine(Image i){
        this.i=i;
    };

    public ProcessingPipeLine shift(Coordinates c){
        shiftImage(c);
        return this;
    }

    public ProcessingPipeLine rotate(int a){
        rotateImage(a);
        return this;
    }

    public Image getResultingImage(){
        return i;
    }

    private void rotateImage(int angle) {
        //shift
    }

    private void shiftImage(Coordinates c) {
        //shift
    }

}

A method call to a method processImage would instantiate such a pipeline and make transparent what and in which order is done: shift, rotate

public Image processImage(Image i, ProcessConfiguration c){
    Image processedImage=i.getCopy();
    processedImage=new ProcessingPipeLine(processedImage)
            .shift(c.getCoordinates())
            .rotate(c.getRotationAngle())
            .getResultingImage();
    return processedImage;
}


答:
Have you considered using some kind of currying? Imagine that you have a class Processee and a class Processor:

```<code>class Processor
{
    private final Processee _processee;

    public Processor(Processee p)
    {
        _processee = p;
    }

    public void process(T1 a1, T2 a2)
    {
        // Process using a1
        // then process using a2
    }
}
</code>```

Now you can replace class Processor by two classes Processor1 and Processor2:

```<code>class Processor1
{
    private final Processee _processee;

    public Processor1(Processee p)
    {
        _processee = p;
    }

    public Processor2 process(T1 a1)
    {
        // Process using argument a1

        return new Processor2(_processee);
    }
}

class Processor2
{
    private final Processee _processee;

    public Processor(Processee p)
    {
        _processee = p;
    }

    public void process(T2 a2)
    {
        // Process using argument a2
    }
}
</code>```

You can then call the operations in the right order using:

```<code>new Processor1(processee).process(a1).process(a2);
</code>```

You can apply this pattern multiple times if you have more than two
parameters. You can also group the arguments as you want, i.e. you do not
need to have each process method take exactly one argument.

Body:
Have you considered using some kind of currying? Imagine that you have a class Processee and a class Processor:

class Processor
{
    private final Processee _processee;

    public Processor(Processee p)
    {
        _processee = p;
    }

    public void process(T1 a1, T2 a2)
    {
        // Process using a1
        // then process using a2
    }
}

Now you can replace class Processor by two classes Processor1 and Processor2:

class Processor1
{
    private final Processee _processee;

    public Processor1(Processee p)
    {
        _processee = p;
    }

    public Processor2 process(T1 a1)
    {
        // Process using argument a1

        return new Processor2(_processee);
    }
}

class Processor2
{
    private final Processee _processee;

    public Processor(Processee p)
    {
        _processee = p;
    }

    public void process(T2 a2)
    {
        // Process using argument a2
    }
}

You can then call the operations in the right order using:

new Processor1(processee).process(a1).process(a2);

You can apply this pattern multiple times if you have more than two
parameters. You can also group the arguments as you want, i.e. you do not
need to have each process method take exactly one argument.


答:
Having over-engineered one or two systems in my career, I will try to answer this from a pragmatic point of view.

My first approach would be to establish the convention, that data must not be modified in the presentation layer. If you work alone you know your own conventions anyway. In a small team you should be able to communicate them easily. Yes, this does not prevent violations at compile time, but unintentional violations should be rare and easy to spot (call hierarchy of a certain setter, for example).

If you absolutely need/want to implement this rule in code, putting the controllers and their respective data objects into a single package each, is the next best thing. Also I would not use protected, but default/package scope (i.e. omit the visibility keyword).
Of the three options you presented, this is the most light weight (and therefore best maintainable and scalable) approach. You shouldn't be too worried about "...making it to difficult to expand the program.", you mereley have to live with potentially a lot of classes in one package. Maybe you can mitigate this by cleverly grouping certain controllers with some objects into their own package.

If this approach also fails, immutable objects are what you want. You could implement them plain (constructor and copy constructor, no setters), with factories/factory methods, or even use the Builder Pattern. Just keep in mind, that the overhead (i.e. boiler plate code) increases significantly with this solution and you should ask yourself if the gain (less time spent hunting/fixing bugs) is really greater than the cost (writing, testing and maintaining boiler plate code).
In fact I would only recommend this solution if you can guarantee, that the objects never need to be modified, and therefore you can ditch the copy code. This does not seem to be the case for your example, though.

Introducing a special getter-interface for each(!) data-class means more overhead than protected/default setters and is only half as strict, as you mentioned yourself: One could always downcast to the actual data-class. To improve this, you could give your data-classes protected or package visibility and put them in the same package as the controllers, but then you are back at square one, with additional interfaces and complexity.

Keeping the controllers and the data-model separated is a good idea. For most applications the model is much more likely to change than the controller logic. And you want to keep that changing part contained, since every change potentially introduces a bug and means additional adaptations in the test- and client code.
By moving and/or wrapping the getters directly into the controller (with or without special interfaces) you also increase the scope of the change. You'd suddenly need to maintain the test- and client code of the controller, instead of just the model, if you want to add/change one field.
Another, simpler problem is, if you need a collection of non-primitive data in your model.

Any software design decision boils down to the question of which solution lets you, your colleagues and users work most efficiently. These three groups will likely have contradictory needs and so it is hard to find the absolutely best solution and trade-offs are almost always a part of it.

Title: MVC like design with interfaces: How to handle basic objects?

Body:
I have an (android) application and decided that the presentation layer will get data only through strict interfaces from the controller. I am at the point where some basic objects need to be passed to the presentation layer, but the objects itself must be in strict read-only mode, because all changes will be handled by the controller.

To make a simple example, imagine a ToDo-App, where the screen needs to display a list of todo items.

The Todo-Item has the fields "title" and "content" with respective getters and setters. Even if I pass an unmodifiable list, the objects in it can be changed. I can think of these alternatives:

put controller and data in one package and make the setters protected.

add an interface to the todo item containing only the getters and passing these objects.

add an interface only to the controller and put all getters there.

for 1)

```<code>public class TodoItem {
    private String title; private String content;
    public String getTitle() ...
    protected String setTitle(..) ...
}
</code>```

for 2)

```<code>public interface ITodoItem {
    public String getTitle();
}

public class TodoItem implements ITodoItem {
    private String title; private String content;

    @Override
    public String getTitle() ...

    public String setTitle(..) ...
}
</code>```

I wonder now what is the more common, smarter etc. option (or are there more?) and what are the arguments?

Alternative 1) for my feeling depends to much on the fact, that the items have to be in the same package making it to difficult to expand the program.

Alternative 2) looks odd to me, because all tiny objects would now become an interface with the getter methods. I am using it and technically I am satisfied (as it prevents me from accidantally changing an object). However, it is not immutable, as the object may be cast back to ToDo-Item and then the original is changed. So this is not good for public apis. Do I really have to clone every object if I want immutability?

Alternative 3) gets messy quick because one controller would then contain all the getters of the tiny objects. This does not comply to "let the object do the work".

What are your experiences and thoughts on this?


问:
If I want write a programming language, what I have to know?
I think about to take this course on coursera:

https://www.coursera.org/course/compilers

What knowledge I absolutely have to have in order to succeeded in this class?

In particularly I'd like to see something like this:

mathematical subject required

engineering/CS required (data structures and so on)

Thanks in advance, Nick.

答:
You could/should read up on the following topics for preparation:

finite state machines

formal and context-free grammar

parse tree

Extended Backus–Naur Form

For a start you could examine the scheme language. It is pretty easy to parse and analyse. You could develop something similar.


问:
Should I use properties for the properties of properties?
Sometimes I use some indirect properties to set or get some other sub-properties,

I give an example

```<code>class Page
{
    public string MainText
    { set { MainParagraph.Text = value; } get { return MainParagraph.Text; }}
    public TextBlock MainParagraph {set; get;}
    public TextBlock FootNotes {set; get;}
}

class TextBlock
{
    public String Text {set; get;}
    public bool   RightToLeft {set; get;}
}
</code>```

Without the MainText property of the Page I have to use myPage.MainParagraph.Text = something and now I use myPage.MainText = something, however one may still use the first alternative. (Should I prevent it?)

Please note Text is not a real property of Page and in this way it may represent some sub-properties but not all of them. Is there any trade off?

For example for the RightToLeft property I prefer myPage.FootNote.RightToLeft = true because it's an specific attribute of each TextBlock but MainText could still be known as the main text of each page.

Is it better to make FootNotes public, but MainParagraph private? Then do I need to define a property in the Page for every property of the MainParagraph?

答:
Making "wrapper properties" like this is fine if it's the cleanest way to implement the API that you want this class to have.

However, the specific example you posted does look questionable to me, mostly because the user of your class can now do exactly the same thing in two different ways: myPage.MainParagraph.Text and myPage.MainText. Since the user doesn't (and shouldn't) know that one simply wraps the other, this raises all sorts of questions he shouldn't have to ask. Yes, documentation can help, but in my opinion the confusion and complication added by this duplicate outweighs the convenience of not having to type those extra two characters.

What you probably want to do is completely hide the TextBlock object, and provide wrappers for only those properties that you want the Page user to have access to. Then if you later decide TextBlock is not the best implementation of Page, it's much easier to change things. Alternatively, you can leave the TextBlock completely exposed with no wrappers, if you think that telling the user "this is how you get the TextBlock object that Page uses" is a better choice for your API.

Edit: Now that you've updated the question, and I can see that your Page class contains two TextBlock objects, I would lean very strongly towards making the two TextBlocks public and having no wrappers. Any attempt to wrap them immediately leads to potential confusion with disambiguating the MainParagraph wrapper from the Footer wrapper from the Header wrapper you'll probably add in version 3.0 from any of the actual TextBlock properties they're all implemented with. It's so much simpler to just expose both and let the TextBlock API do its job.


问:
Where to put utility classes in PHP MVC?
I am creating a PHP project using the MVC pattern.
You can see the directory structure below.

My question: where can I put utility classes like Email and Date?

Project directory structure:

```<code>- app/
   - Models/
   - Controllers/
   - Views/
- vendor/
- composer.json
- composer.lcok
</code>```

答: Like any other utility class/helper function/convenience whatever, where to put it depends on who's using it. If only M uses it, then maybe it belongs in the Model folder. If your M, V and C are all using Dates, then maybe Date belongs in a separate folder from all three. You don't have to put every piece of code in one of those three folders.</p>

ContentLicense: CC BY-SA 4.0


问:
3 tier architecture in .NET web applications
Nowadays most systems are designed as web apps. In the .NET world the famous three tier architecture is usually translated like this.

Front End (Web Application)

Middle Tier (custom DLLs using an ORM to access and process data)

Back End (SQL Server, Oracle, MySQL)

To me, the middle tier is not actually the middle tier because regardless of how isolated the mid tier is, it executes in the context of a web server (as it resides in the DLLs) and essentially a part of the web application.

My Questions:

Is it correct to say that a 3 tier arch is a simple 2 tier arch?

Is it correct to design the apps, that requiring heavy data processing, with no physically separate middle tier?

What options are available for the middle tier other than hosting it in WCF or Windows Service?

答:
Whether you place the "Middle Tier" code in DLLs loaded by the Front End site or place it into a separate web service application is just a detail. This placement decision does not change the code architecture in a meaningful way. It's more of a deployment decision.

No, the tiers are not defined by physical deployment decisions but by code architecture and data flow.

I'll replace the word "correct" by "advisable" in your question and answer that one. What's advisable is what allows you to be most productive. A "Middle Tier" is used when needed (it is not strictly required). For example it can be helpful to untangle logic from UI code and it can allow for having multiple Front Ends using the same business logic.

Again, you can place the "Middle Tier" code anywhere you like. It can be in a DLL, in a WCF web service or in a Windows Service. This is purely a deployment decision. Relevant concerns are simplicity, fault isolation, security and performance.

The term "Back End" means many things to different people. Complex real-world systems often consist of many components. There often is not a single component you can identify as the "last layer". "Back End" is a relative term.


问:
Is static universally "evil" for unit testing and if so why does Resharper recommend it?
I have found that there are only 3 ways to unit test (mock/stub) dependencies that are static in C#.NET:

Moles

TypeMock

JustMock

Given that two of these are not free and one has not hit release 1.0, mocking static stuff is not too easy.

Does that make static methods and such "evil" (in the unit testing sense)?  And if so, why does resharper want me to make anything that can be static, static? (Assuming resharper is not also "evil".)

Clarification:
I am talking about the scenario when you want to unit test a method and that method calls a static method in a different unit/class.  By most definitions of unit testing, if you just let the method under test call the static method in the other unit/class then you are not unit testing, you are integration testing.  (Useful, but not a unit test.)

答:
There's no two ways about it.   ReSharper's suggestions and several useful features of C# would not be used as often if you were writing isolated atomic unit tests for all your code.

For instance, if you have a static method and you need to stub it out, you can't unless you use a profile based isolation framework.   A call-compatible workaround is to change the top of the method to use lambda notation.   For example:

BEFORE:

```<code>    public static DBConnection ConnectToDB( string dbName, string connectionInfo ) {
    }
</code>```

AFTER:

```<code>    public static Func<string, string, DBConnection> ConnectToDB (dbName, connectionInfo ) {
    };
</code>```

The two are call-compatible.  Callers don't have to change.   The body of the function remains the same.

Then in your Unit-Test code, you can stub this call like so (assuming it's in a class called Database) :

```<code>        Database.ConnectToDB = (dbName, connectionInfo) => { return null|whatever; }
</code>```

Be careful to replace it with the original value after you're done.  You can do that via a try/finally or, in your unit-test clean up, the one that gets called after every test, write code such as this:

```<code>    [TestCleanup]
    public void Cleanup()
    {
        typeof(Database).TypeInitializer.Invoke(null, null);
    }
</code>```

which will re-invoke the static initializer of your class.

Lambda Funcs are not as rich in support as regular static methods, so this approach has the following undesirable side-effects:

If the static method was an extension method, you have to change it to a non-extension method first.  Resharper can do this for you automatically.

If any of the data types of the static methods are an embedded-interop assembly, such as for Office, you have to wrap the method, wrap the type or change it to type 'object'.

You can no longer use Resharper's change-signature refactoring tool.

But let's say you avoid statics altogether, and you convert this to an instance method.  It's still not mockable unless the method is either virtual or implemented as part of an interface.

So in reality, anyone who suggests the remedy to stubbing static methods is to make them instance methods, they would also be against instance methods that are not virtual or part of an interface.

So why does C# have static methods?
Why does it allow for non-virtual instance methods?

If you use either of these "Features", then you simply cannot create isolated methods.

So when do you use them?

Use them for any code that you don't expect anyone to ever want to stub out.  Some examples:
    the Format() method of the String class
    the WriteLine() method of the Console class
    the Cosh() method of the Math class

And one more thing..  Most people won't care about this, but if you can about the performance of an indirect call, that's another reason to avoid instance methods.  There are cases when it's a performance hit.   That's why non-virtual methods exist in the first place.

Body:
There's no two ways about it.   ReSharper's suggestions and several useful features of C# would not be used as often if you were writing isolated atomic unit tests for all your code.

For instance, if you have a static method and you need to stub it out, you can't unless you use a profile based isolation framework.   A call-compatible workaround is to change the top of the method to use lambda notation.   For example:

BEFORE:

    public static DBConnection ConnectToDB( string dbName, string connectionInfo ) {
    }

AFTER:

    public static Func<string, string, DBConnection> ConnectToDB (dbName, connectionInfo ) {
    };

The two are call-compatible.  Callers don't have to change.   The body of the function remains the same.

Then in your Unit-Test code, you can stub this call like so (assuming it's in a class called Database) :

        Database.ConnectToDB = (dbName, connectionInfo) => { return null|whatever; }

Be careful to replace it with the original value after you're done.  You can do that via a try/finally or, in your unit-test clean up, the one that gets called after every test, write code such as this:

    [TestCleanup]
    public void Cleanup()
    {
        typeof(Database).TypeInitializer.Invoke(null, null);
    }

which will re-invoke the static initializer of your class.

Lambda Funcs are not as rich in support as regular static methods, so this approach has the following undesirable side-effects:

If the static method was an extension method, you have to change it to a non-extension method first.  Resharper can do this for you automatically.

If any of the data types of the static methods are an embedded-interop assembly, such as for Office, you have to wrap the method, wrap the type or change it to type 'object'.

You can no longer use Resharper's change-signature refactoring tool.

But let's say you avoid statics altogether, and you convert this to an instance method.  It's still not mockable unless the method is either virtual or implemented as part of an interface.

So in reality, anyone who suggests the remedy to stubbing static methods is to make them instance methods, they would also be against instance methods that are not virtual or part of an interface.

So why does C# have static methods?
Why does it allow for non-virtual instance methods?

If you use either of these "Features", then you simply cannot create isolated methods.

So when do you use them?

Use them for any code that you don't expect anyone to ever want to stub out.  Some examples:
    the Format() method of the String class
    the WriteLine() method of the Console class
    the Cosh() method of the Math class

And one more thing..  Most people won't care about this, but if you can about the performance of an indirect call, that's another reason to avoid instance methods.  There are cases when it's a performance hit.   That's why non-virtual methods exist in the first place.


问:
eBook editions of programming books
(I'll get my justification for why this is on topic in early: programming books tend to have fairly specific formatting needs - code samples, tables, images and graphs - which are not common to all book types and are not necessarily well handled by eBook readers.  Similarly they're used in different ways - you often dip in and out rather than read cover to cover.)

I've just noticed that Don't Make Me Think by Steve Krug is available as an eBook edition for the Kindle (and presumably also for other readers) which set me thinking.

There are certain advantages to eBook readers for tech books - primarily that you can carry a massive library of what would be heavy physical books around very easily.  The downside is that certain eBook readers allegedly aren't particularly well equipped to cope with tables, code samples and so on and a book like Don't Make Me Think presumably makes extensive use of these sorts of things.

So, the question, what are your experiences of reading and using programming books on an eBook reader and would you recommend it? I'm specifically interested in the latest generation Kindle but happy to hear about all devices - might be useful to state which one you use in the answer.

答:
I don't have any experience with the Kindle, but I have read tech books on a Sony PRS-505. It has been a mixed experience.

The principal issue was that most programming books release a PDF and call that an eBook. Those that come in an eBook-friendly format (such as ePub) are more reader-friendly. PDFs are a bit of a pain because your options are to either live with the tiny font and strain your eyes, or increase the font, but absolutely destroy code samples.

I've tried various converters from PDF to ePub, but they didn't work very well.

I eventually settled on flipping the reader to landscape mode to squeeze some more size out of the default font settings. Biggest lesson learned: if you want to read programming books in PDF on an eReader make sure its screen has roughly the same dimensions as a PDF page.

In the end I gave up on it, unless it's a free eBook. It's just not worth paying for a PDF that I won't be able to comfortably read when I could just buy a printed version of the book.

Title: eBook editions of programming books


问:
Why aren't "fat binaries" more widely used for cross-platform applications?
As far as I know, so-called "fat binaries"--executable files that contain machine code for multiple systems--are only really used on Apple PCs, and even there it seems like they only used them because they needed to transition from PowerPC to x86.

These days a lot of software is cross-platform, and it seems like making a single fat binary would be in many ways simpler than keeping track of a dozen or so different downloads for each combination of operating system and architecture, not to mention somehow conveying to the customer which one they want.

I can come up with plenty of guesses as to why this approach never caught on, for instance:

A lack of cross-compilation tools making multi-OS binaries infeasible

You need to test the code on each OS anyway, so you already have to have systems that can compile natively for each OS

Apparently 32-bit programs "just work" on 64-bit machines already

Dynamic linking works differently on each OS, so a "fat library" might not work even if a "fat application" would

But since I always work with a library or framework that hides all these OS-specific and architecture-specific details from me, I don't know how true any of that really is, or if there are even more issues I don't know about. So, what are the actual reasons why fat binaries aren't generally used to create multi-architecture and/or multi-OS software? (outside of Apple)

答:
Part of the reasons why fat binaries did not succeed is that there is more than the ABI & processor (actually, instruction set) specifications to invalidate a binary executable. A binary executable often depends a lot on other resources, in particular dynamic libraries (see the DLL hell), external services (think of DBMS like PostGreSQL ....), system configuration (e.g. location of configuration files under /etc/ on Linux), etc. etc....

Just for Linux/x86-64 it is in practice difficult to make a binary executable able to run on every Linux distributions (because it is often tied to specific versions of libc or of libstdc++). FatELF exists but is not very successful.

Even with a well defined ABI and instruction set, the optimization would be different on various processor brands - see the -mtune=native x86 optimization flag of GCC.

Apple partly succeeded in having fat binaries only because they provide a very closed eco-system of computing resources.

Free software is another way to solve your portability concern:  If an application is free software (carefully coded for portability), it is quite easily ported to similar systems. And even if the original source code does not work as intended on your system, you could adapt it (or pay someone to do the work) usually reasonably easily (of course, free software tied to particular OS or ABI or processor is not easy to port, you'll pay more efforts for that). And standards like POSIX or Linux Standard Base also help.

You could pay (or ask) someone to port some (free) software with available source code, but it is unrealistic to port a binary executable.

At last, several frameworks exist to help porting on several operating systems (provided source code is available), e.g. Qt & POCO.

Even using a well specified bytecode like the JVM is not always a guarantee of portability: some Java applications are well known to not be portable (e.g. because they expect some particular file hierarchy and naming).

BTW, computer systems are probably much less heterogeneous today than in the 1980s or early 1990s (or in the mainframe era).

At last, fat binaries are fat: you will spend a lot of resources (build time, bandwidth, executable size) for a portability issue that might not concern a lot of people. Remember the aphorism: "there is no portable software, only software which has been ported" (to some particular systems).