问:
How other thread can show the incremented value unless the 1st thread reaches the return statement?
My code is given below.

In the for loop I am getting unexpected output i.e.

before completing the execution of for loop by 1st thread the 2nd thread comes in for loop and shows incremented value.

```<code>public class ThreadSafe {
    public static void main(String[] args) throws InterruptedException {
        System.out.println("main()");

        B b=new B("1st Thread");
        B b1=new B("2nd Thread");
        B b2=new B("3rd Thread");
        b.start();
        b1.start();
        b2.start();
    }
}

class MyCounter {
    private static int count;

    public static int getCount(){
        for(int m=0;m<2;m++){
            System.out.println(count+" "+Thread.currentThread().getName());
        }

        return count++;
    }
}

class B extends Thread{
    public B(String tname) {
        super(tname);
    }

public void run() {
    MyCounter.getCount();
    }
}
</code>```

The question is when 1st thread executes for loop then other threads executing return statement is this the reason of showing increment value or something else?

How other thread can show the incremented value unless the 1st thread reaches the return statement?

答:
first 2 points to make:

there is not guarantee that the thread's execution will be interleaved, short pieces of code will likely complete uninterrupted. Add sleeps if you want to lessen this effect.

count++ is not thread safe, it expands to int tmp=count; count=tmp+1; and the thread may be interrupted between the tmp=count and count=tmp+1. Instead use an AtomicInt and incrementAndGet.

The increment of the static count may not be visible to the other thread, it takes a while before changes to a variable become visible to other threads. Using a volatile field will lessen that but you will still see points 1 and 2 in effect.

Also print statements are buffered before being written out so the order of the print statements don't necessarily mean that they were called in that order.


问:
Adapter Pattern: Design Patterns
So far as I know, there are two forms of the Adapter Pattern: the class adapter and the object adapter. Could someone please explain to me the following limitation of the class adapter and why it is not a limitation of the object adapter:

a class adapter is not suitable when we want to adapt a class and all of its subclasses.

I guess the following is considered a limitation of the object adapter:

with an object adapter it is harder to override Adaptee behaviour than with a class adapter.

Why is that?

答:
A class adapter IS a subclass, so you certainly shouldn't use it to adapt multiple subclasses. Even assuming that multiple inheritance is available in your language of choice, this would create an unmaintainable chain of inheritance.

An object adapter wraps an object and thus can't be used to modify the behaviour of the class of the object it's wrapping. It can, however, decide how to use that behaviour.

ContentLicense: CC BY-SA 3.0

Title: Adapter Pattern: Design Patterns


问:
Where should an object in CQRS+ES be fully initialized: in the constructor, or when applying the first event?
There appears to be widespread agreement in the OOP community that the class constructor should not leave an object partly or even fully uninitialized.

What do I mean by "initialization"? Roughly speaking, the atomic process that brings a newly created object into a state where all of its class invariants hold. It should be the first thing that happens to an object, (it should only run once per object,) and nothing should be permitted to get hold of an un-initialized object. (Thus the frequent advice to perform object initialization right in the class constructor. For the same reason, Initialize methods are often frowned upon, as these break apart the atomicity and make it possible to get hold of, and use, an object that is not yet in a well-defined state.)

Problem: When CQRS is combined with event sourcing (CQRS+ES), where all state changes of an object are caught in an ordered series of events (event stream), I am left wondering when an object actually reaches a fully-initialized state: At the end of the class constructor, or after the very first event has been applied to the object?

Note: I'm refraining from using the term "aggregate root". If you prefer, substitute it whenever you read "object".

Example for discussion: Assume that each object is uniquely identified by some opaque Id value (think GUID). An event stream representing that object's state changes can be identified in the event store by the same Id value: (Let's not worry about correct event order.)

interface IEventStore
{
    IEnumerable<IEvent> GetEventsOfObject(Id objectId);
}
```

<p>Assume further that there are two object types <code>Customer</code> and <code>ShoppingCart</code>. Let's focus on <code>ShoppingCart</code>: When created, shopping carts are empty and must be associated with exactly one customer. That last bit is a class invariant: A <code>ShoppingCart</code> object that is not associated to a <code>Customer</code> is in an invalid state.</p>

<p>In traditional OOP, one might model this in the constructor:</p>

<pre class="lang-cs prettyprint-override"><code>partial class ShoppingCart
{
    public Id Id { get; private set; }
    public Customer Customer { get; private set; }

    public ShoppingCart(Id id, Customer customer)
    {
        this.Id = id;
        this.Customer = customer;
    }
}
</code>```

I am however at a loss how to model this in CQRS+ES without ending up with deferred initialization. Since this simple bit of initialization is effectively a state change, wouldn't it have to be modelled as an event?:

partial class CreatedEmptyShoppingCart
{
    public ShoppingCartId { get; private set; }
    public CustomerId { get; private set; }
}
// Note: `ShoppingCartId` is not actually required, since that Id must be
// known in advance in order to fetch the event stream from the event store.
```

This would obviously have to be the very first event in any ShoppingCart object's event stream, and that object would only be initialized once the event were applied to it.

So if initialization becomes part of the event stream "playback" (which is a very generic process that would likely work the same, whether for a Customer object or a ShoppingCart object or any other object type for that matter)…

Should the constructor be parameter-less and do nothing, leaving all work to some void Apply(CreatedEmptyShoppingCart) method (which is much the same as the frowned-upon Initialize())?

Or should the constructor receive an event stream and play it back (which makes initialization atomic again, but means that each class' constructor contains the same generic "play back & apply" logic, i.e. unwanted code duplication)?

Or should there be both a traditional OOP constructor (as shown above) that properly initializes the object, and then all events but the first are void Apply(…)-ied to it?

I do not expect of answer to provide a fully working demo implementation; I'd already be very happy if someone could explain where my reasoning is flawed, or whether object initialization really is a "pain point" in most CQRS+ES implementations.

答:
In my opinion, I think the answer is more like your suggestion #2 for existing aggregates; for new aggregates more like #3 (but processing the event as you suggested).

Here's some code, hope it is of some help.

```<code>public abstract class Aggregate
{
    Dictionary<Type, Delegate> _handlers = new Dictionary<Type, Delegate>();

    protected Aggregate(long version = 0)
    {
        this.Version = version;
    }

    public long Version { get; private set; }

    protected void Handles<TEvent>(Action<TEvent> action)
        where TEvent : IDomainEvent
    {
        this._handlers[typeof(TEvent)] = action;
    }

    private IList<IDomainEvent> _pendingEvents = new List<IDomainEvent>();

    // Apply a new event, and add to pending events to be committed to event store
    // when transaction completes
    protected void Apply(IDomainEvent @event)
    {
        this.Invoke(@event);
        this._pendingEvents.Add(@event);
    }

    // Invoke handler to change state of aggregate in response to event
    // Event may be an old event from the event store, or may be an event triggered
    // during the lifetime of this instance.
    protected void Invoke(IDomainEvent @event)
    {
        Delegate handler;
        if (this._handlers.TryGetValue(@event.GetType(), out handler))
            ((Action<TEvent>)handler)(@event);
    }
}

public class ShoppingCart : Aggregate
{
    private Guid _id, _customerId;

    private ShoppingCart(long version = 0)
        : base(version)
    {
         // Setup handlers for events
         Handles<ShoppingCartCreated>(OnShoppingCartCreated);
         // Handles<ItemAddedToShoppingCart>(OnItemAddedToShoppingCart);
         // etc...
    }

    public ShoppingCart(long version, IEnumerable<IDomainEvent> events)
        : this(version)
    {
         // Replay existing events to get current state
         foreach (var @event in events)
             this.Invoke(@event);
    }

    public ShoppingCart(Guid id, Guid customerId)
        : this()
    {
        // Process new event, changing state and storing event as pending event
        // to be saved when aggregate is committed.
        this.Apply(new ShoppingCartCreated(id, customerId));
    }

    private void OnShoppingCartCreated(ShoppingCartCreated @event)
    {
        this._id = @event.Id;
        this._customerId = @event.CustomerId;
    }
}

public class ShoppingCartCreated : IDomainEvent
{
    public ShoppingCartCreated(Guid id, Guid customerId)
    {
        this.Id = id;
        this.CustomerId = customerId;
    }

    public Guid Id { get; private set; }
    public Guid CustomerID { get; private set; }
}
</code>```

Body:
In my opinion, I think the answer is more like your suggestion #2 for existing aggregates; for new aggregates more like #3 (but processing the event as you suggested).

Here's some code, hope it is of some help.

public abstract class Aggregate
{
    Dictionary<Type, Delegate> _handlers = new Dictionary<Type, Delegate>();

    protected Aggregate(long version = 0)
    {
        this.Version = version;
    }

    public long Version { get; private set; }

    protected void Handles<TEvent>(Action<TEvent> action)
        where TEvent : IDomainEvent
    {
        this._handlers[typeof(TEvent)] = action;
    }

    private IList<IDomainEvent> _pendingEvents = new List<IDomainEvent>();

    // Apply a new event, and add to pending events to be committed to event store
    // when transaction completes
    protected void Apply(IDomainEvent @event)
    {
        this.Invoke(@event);
        this._pendingEvents.Add(@event);
    }

    // Invoke handler to change state of aggregate in response to event
    // Event may be an old event from the event store, or may be an event triggered
    // during the lifetime of this instance.
    protected void Invoke(IDomainEvent @event)
    {
        Delegate handler;
        if (this._handlers.TryGetValue(@event.GetType(), out handler))
            ((Action<TEvent>)handler)(@event);
    }
}

public class ShoppingCart : Aggregate
{
    private Guid _id, _customerId;

    private ShoppingCart(long version = 0)
        : base(version)
    {
         // Setup handlers for events
         Handles<ShoppingCartCreated>(OnShoppingCartCreated);
         // Handles<ItemAddedToShoppingCart>(OnItemAddedToShoppingCart);
         // etc...
    }

    public ShoppingCart(long version, IEnumerable<IDomainEvent> events)
        : this(version)
    {
         // Replay existing events to get current state
         foreach (var @event in events)
             this.Invoke(@event);
    }

    public ShoppingCart(Guid id, Guid customerId)
        : this()
    {
        // Process new event, changing state and storing event as pending event
        // to be saved when aggregate is committed.
        this.Apply(new ShoppingCartCreated(id, customerId));
    }

    private void OnShoppingCartCreated(ShoppingCartCreated @event)
    {
        this._id = @event.Id;
        this._customerId = @event.CustomerId;
    }
}

public class ShoppingCartCreated : IDomainEvent
{
    public ShoppingCartCreated(Guid id, Guid customerId)
    {
        this.Id = id;
        this.CustomerId = customerId;
    }

    public Guid Id { get; private set; }
    public Guid CustomerID { get; private set; }
}


问:
I am making 4-5x more story points than average, but producing bugs at half the rate. Graphs say it's 2x more bugs, how to deal with that?
So it is generally accepted that top tier programmers can produce an order of magnitude more/better code than their more average peers.

It's also generally accepted that the rate of errors made in code is relatively constant for programmers.

Instead, it tends to be impacted by the processes used when writing the code and after the code is written. (As I understand it) Humans tend to make mistakes at a fairly constant rate - better programmers just notice more of them and are quicker to fix them.

Note that both of above assertions come from Code Complete by Steve McConnell - so it's not a matter of differing perspectives.

So I've started to see this recently in my code. I can hammer out about 4-5x the amount of code as many of my peers (measured by story points estimated by the team), with higher quality (based on performance metrics and number of changes made after check-in). But I still make mistakes. Between better unit tests, a better understanding of what the code is doing, and a better eye for issues when doing code reviews I'm not producing 4-5x the number of bugs.

But I'm still producing about twice as many bugs found by QA as other developers on my team. As you might imagine, this causes some problems with non-technical folks doing metric measurements (read: my boss).

I've tried to point out that I'm producing bugs at half the rate of my peers (and fix twice as many), but it's a hard sell when there's graphs saying I produce twice as many bugs.

So, how to deal with the fact that increased productivity will lead to an increased number of bugs?

答:
I think you're mixing your concerns.  And there's nothing on your side that you need to change.

Productivity is a hint at how quickly a project will be completed.  Project managers and everybody else like to know when the project will deliver.  Higher or faster productivity means we'll see the project deliver sooner.

Rate of bugs isn't tied to productivity but rather to the size of the project.  For example, you may have N bugs per Y lines of code.  There is nothing within that metric that says (or cares!) how quickly those lines of code are written.

To tie that together, if you have higher productivity, yes, you'll "see" the bugs being written more quickly.  But you were going to have that number of bugs anyway since it's tied to the size of the project.

If anything, higher productivity means you'll have more time at the end of the project to hunt those bugs down or the developer will be faster in finding the bugs they created.1

To address the more personal aspects of your question.

If your boss is looking strictly at the number of bugs you produce as opposed to the rate of bugs you produce, an educational session is in order.  Number of bugs created is meaningless without a backing rate.

To take that example to the extreme, please tell your boss I want double your salary.  Why?  I have created absolutely no bugs on your project and I am therefore a much superior  programmer than you.  What?  He's going to have a problem that I haven't produced a single line of code to benefit your project?  Ah.  Now we have understanding of why rate is important.

It sounds like your team has the metrics to evaluate bugs per story point.  If nothing else, it's better than being measured by raw number of bugs created.  Your best developers should be creating more bugs because they're writing more code.  Have your boss throw out that graph or at least throw another series behind it showing how many story points (or whatever business value you measure) alongside the number of bugs.  That graph will tell a more accurate story.

1
 This particular comment has attracted far more attention than it was intended to.  So let's be a bit pedantic (surprise, I know) and reset our focus on this question.

The root of this question is about a manager looking at the wrong thing(s).  They are looking at raw bug totals when they should be looking at generation rate versus number of tasks completed. Let's not obsess over measuring against "lines of code" or story points or complexity or whatever.  That's not the question at hand and those worries distract us from the more important question.

As laid out in the links by the OP, you can predict a certain number of bugs in a project purely by the size of the project alone.  Yes, you can reduce this number of bugs through different development and testing techniques.  Again, that wasn't the point of this question.  To understand this question, we need to accept that for a given size project and development methodology, we'll see a given number of bugs once development is "complete."

So let's finally get back to this comment that a few completely misunderstood.  If you assign comparably sized tasks to two developers, the developer with a higher rate of productivity will complete their task before the other.  The more productive developer will therefore have more time available at the end of the development window.  That "extra time" (as compared to the other developer) can be used for other tasks such as working on the defects that will percolate through a standard development process.

We have to take the OP at their word that they are more productive than other developers.  Nothing within those claims implies that the OP or other more productive developers are being slipshod in their work. Pointing out that there would be less bugs if they spent more time on the feature or suggesting that debugging isn't part of this development time misses what has been asked. Some developers are faster than others and produce comparable or better quality work.  Again, see the links that the OP lays out in their question.


问:
Buyer vs Seller on UML Model
I'm modeling an Online Classified System where, naturally, who sells also can buy and vice-versa.

The question is: should I have two different Actors, Buyer and Seller or I could have, say, an actor Client capable either buy and sell?

How do you approach this Model?

Cheers,

答: If somebody is buying and somebody is selling, then you have two actors.  They may be of the same "type", but they are still separate actors.</p>

Title: Buyer vs Seller on UML Model


问:
Why do arrays in Java not override equals()?
I was working with a HashSet the other day, which has this written in the spec:

[add()] adds the specified element e to this set if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2))

I was using char[] in the HashSet until I realized that, based on this contract, it was no better than an ArrayList! Since it's using the non-overridden .equals(), my arrays will only be checked for reference equality, which is not particularly useful. I know that Arrays.equals() exists, but that doesn't help when one is using collections such as HashSet.

So my question is, why would Java arrays not override equals?

答:
Overriding array equals() and hashCode() to depend on content would make them similar to collections - mutable types with non-constant hashCode(). Types with changing hashCode() behave poorly when stored in hash-tables and other applications relying on hashCode() fixed value.

```<code>Set<List<Integer>> data = new HashSet<List<Integer>>();
List<Integer> datum = new ArrayList<Integer>();
datum.add(1);
data.add(datum);
assert data.contains(datum); // true
datum.add(2);
assert data.contains(datum); // false, WAT???
</code>```

Arrays on other hand has trivial hashCode(), can be used as hash-table keys and are still mutable.

```<code>Set<int[]> data = new HashSet<int[]>(67);
int[] datum = new int[]{1, 2};
data.add(datum);
System.out.println(data.contains(datum)); //true
datum[0] = 78;
System.out.println(data.contains(datum)); //true
//PROFIT!!!
</code>```

Body:
Overriding array equals() and hashCode() to depend on content would make them similar to collections - mutable types with non-constant hashCode(). Types with changing hashCode() behave poorly when stored in hash-tables and other applications relying on hashCode() fixed value.

Set<List<Integer>> data = new HashSet<List<Integer>>();
List<Integer> datum = new ArrayList<Integer>();
datum.add(1);
data.add(datum);
assert data.contains(datum); // true
datum.add(2);
assert data.contains(datum); // false, WAT???

Arrays on other hand has trivial hashCode(), can be used as hash-table keys and are still mutable.

Set<int[]> data = new HashSet<int[]>(67);
int[] datum = new int[]{1, 2};
data.add(datum);
System.out.println(data.contains(datum)); //true
datum[0] = 78;
System.out.println(data.contains(datum)); //true
//PROFIT!!!


问:
Polling vs events pros and cons in JavaScript
I'm bit of a novice to JavaScript so I've been wondering on positive and negative sides of using polling compared to using events in JavaScript? When does one use one or the other?

By polling I consider any effect that is triggered on something that repeats itself usually using setTimeout. But also for example:

```<code>function render() {
   Bloop.renderComponent(box, document.body);
   requestAnimationFrame(render);
}
</code>```

Is also polling since requestAnimationFrame(render) which is called before each frame is called.

Basically anything that fits this definition

答:
This is a bit of a "which is better, fish or the colour orange" type of question, but in terms of the general behaviour of JavaScript, and particularly the more functional side of it's nature it is probably more idiomatic to use events to react to changes of state than it is to have a timed polling system.

It is a lot more flexible and less confusing to be adding and removing event listeners as your application starts to grow. Polling is easier to conceptualise when you are first imagining everything clocking in to a central location, but as your application gets more complex that is liable to get increasingly difficult to do, whereas events can come from anywhere and go to anywhere so they are much less tightly coupled.

Also when an event is triggered and there is nobody to hear it, nothing happens. If you have a whole lot of timeout based polling loops, you may find that things are happening after the main system crashed as timeouts trigger, which makes debugging the problem or following up any logs more confusing.

Practically if you are animating things, you will probably want to use some degree of polling for your animation loop and events to communicate when to trigger other animations or when interactions occur, so you're likely to want to use both.


问:
Generating PDF files using individual template components
EDIT:  Updated flow diagram to better explain the (likely unnecessary) complexity of what I'm doing.

We at the company I work for are attempting to create complex PDF files using Java iText (the free version 2.1 line).  The documents are built piece-by-piece from individual "template" files, which are added to the final document one after another using the PdfStamper class, as well as filled using AcroForms.

The current design performs a loop which runs for each template that needs to be added in order (as well as the custom logic needed to fill each).  In each iteration of the loop, it does the following:

Creates a PdfReader to open the template file

Creates a PdfStamper that reads from the PdfReader and writes to a "template buffer"

Fills AcroForm fields, as well as measures the height of the template by getting the location of an "end" AcroField.

Closes the PdfReader and PdfStamper

Creates a PdfReader to read a "working buffer" that stores the current final document in progress

Creates a PdfStamper that reads from the PdfReader and writes to a "storage buffer"

Closes the PdfReader, opens a new PdfReader to the "template buffer"

Imports the page from the "template buffer," adds it to the ContentByte of the PdfStamper

Closes the PdfReader and PdfStamper

Swaps the "storage buffer" with the "working buffer" in order to be ready to repeat.

Here is a diagram visually explaining the above process, which is performed for each iteration of the "loop" that performs each template:

However, as discovered through this Stack Overflow question (where example code can also be viewed) and the response by iText author Bruno Lowagie, this methodology of using the PdfStamper can cause significant issues.  "Abusing" the PdfStamper by creating and closing the stamper too many times can cause corruptions in the resulting file that only effect some programs, generating a seemingly good document that may fail in certain contexts.

What is the alternative?  Mr. Lowagie's response suggests that there is a simpler or more direct way to use PdfStampers, though I do not quite understand it myself yet.  Could this be done using only a single stamper?  Could it be done without using a rotating series of buffers?

答:
I'm always disappointed when I read "we are using iText 2.1" because that's really not a wise choice as explained here, but this is a question about design, so here is a possible approach:

You create a new document Document document = new Document(); (step 1), you create a PdfWriter instance (step 2), you open the document (step 4), and you add content in a loop (step 4):

You have different templates, and by templates we mean: existing PDF documents with fillable fields (AcroForms). You fill them out using PdfStamper and AcroFields (see your code on StackOverflow). This results in separate "flattened" form snippets kept in memory.

If you want to keep these snippets together, you can do so by creating a Document/PdfWriter instance to create a new PDF in memory that combines all the snippets that belong together. You get a snippet like this: PdfImportedPage snippet = writer.getImportedPage(reader, 1); and you add the snippet to the writer using the addTemplate() method.

You get the combined result using PdfImportedPage combined = writer.getImportedPage(reader, 1);, you wrap the result in an image like this: Image image = Image.getInstance(combined); You add the image to the document: document.add(image);

Step 2 could be omitted. You could add the different snippets straight to the document that is initially created. Repeats steps 1 to 3 as many times as needed, and close the document (step 5).

Omitting step 2 will result in a lower XObject nesting count, but keeping step 2 isn't problematic.

In pseudo code, we'd have:

[1.] The outer loop (the large part to the right of the schema, marked PdfWriter)

```<code>// step 1
Document document = new Document();
// step 2
PdfWriter writer = PdfWriter.getInstance(document, os);
// step 3
document.open();
// step 4
for (int i = 0; i < parameters.length; i++)
    document.add(getSnippetCombination(writer, parameters[i]));
// step 5
document.close();
</code>```

[2.] The creation of one unit (the arrow marked PdfWriter in the middle)

```<code>public Image getSnippetCombination(PdfWriter w, Parameters parameters) {
    // step 1
    Document document = new Document();
    // step 2
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfWriter writer = PdfWriter.getInstance(document, baos);
    // step 3
    document.open();
    // step 4
    PdfContentByte canvas = writer.getDirectContent();
    for (int i = 0; i < parameters.getNumberOfSnippets(); i++)
        canvas.addTemplate(getSnippet(writer, parameters.getSnippet(i)),
            parameters.getX(i), parameters.getY(i));
    // step 5
    document.close();
    // Convert PDF in memory to From XObject wrapped in Image object
    PdfReader reader = new PdfReader(baos.toByteArray());
    PdfImportedPage page = w.getImportedPage(reader, 1);
    return Image.getInstance(page);
}
</code>```

[3.] Filling out data in separate snippets (the arrows marked PdfStamper)

```<code>public PdfTemplate getSnippet(PdfWriter w, Snippet snippet) {
    // Using PdfStamper to fill out the fields
    PdfReader reader = new PdfReader(snippet.getBytes());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfStamper stamper = new PdfStamper(reader, baos);
    stamper.setFormFlattening(true);
    AcroFields form = stamper.getAcroFields();
    // fill out the fields; you've already implemented this
    stamper.close();
    // return the template
    PdfReader reader = new PdfReader(baos.toByteArray());
    return w.getImportedPage(reader, 1);
}
</code>```

There may be better solutions, for instance involving XFA, but I don't know if that's feasible as I don't know if the templates (the light blue part in my schema) are always the same. It would also involve creating new templates in the XML Forms Architecture.

Body:
I'm always disappointed when I read "we are using iText 2.1" because that's really not a wise choice as explained here, but this is a question about design, so here is a possible approach:

You create a new document Document document = new Document(); (step 1), you create a PdfWriter instance (step 2), you open the document (step 4), and you add content in a loop (step 4):

You have different templates, and by templates we mean: existing PDF documents with fillable fields (AcroForms). You fill them out using PdfStamper and AcroFields (see your code on StackOverflow). This results in separate "flattened" form snippets kept in memory.

If you want to keep these snippets together, you can do so by creating a Document/PdfWriter instance to create a new PDF in memory that combines all the snippets that belong together. You get a snippet like this: PdfImportedPage snippet = writer.getImportedPage(reader, 1); and you add the snippet to the writer using the addTemplate() method.

You get the combined result using PdfImportedPage combined = writer.getImportedPage(reader, 1);, you wrap the result in an image like this: Image image = Image.getInstance(combined); You add the image to the document: document.add(image);

Step 2 could be omitted. You could add the different snippets straight to the document that is initially created. Repeats steps 1 to 3 as many times as needed, and close the document (step 5).

Omitting step 2 will result in a lower XObject nesting count, but keeping step 2 isn't problematic.

In pseudo code, we'd have:

[1.] The outer loop (the large part to the right of the schema, marked PdfWriter)

// step 1
Document document = new Document();
// step 2
PdfWriter writer = PdfWriter.getInstance(document, os);
// step 3
document.open();
// step 4
for (int i = 0; i < parameters.length; i++)
    document.add(getSnippetCombination(writer, parameters[i]));
// step 5
document.close();

[2.] The creation of one unit (the arrow marked PdfWriter in the middle)

public Image getSnippetCombination(PdfWriter w, Parameters parameters) {
    // step 1
    Document document = new Document();
    // step 2
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfWriter writer = PdfWriter.getInstance(document, baos);
    // step 3
    document.open();
    // step 4
    PdfContentByte canvas = writer.getDirectContent();
    for (int i = 0; i < parameters.getNumberOfSnippets(); i++)
        canvas.addTemplate(getSnippet(writer, parameters.getSnippet(i)),
            parameters.getX(i), parameters.getY(i));
    // step 5
    document.close();
    // Convert PDF in memory to From XObject wrapped in Image object
    PdfReader reader = new PdfReader(baos.toByteArray());
    PdfImportedPage page = w.getImportedPage(reader, 1);
    return Image.getInstance(page);
}

[3.] Filling out data in separate snippets (the arrows marked PdfStamper)

public PdfTemplate getSnippet(PdfWriter w, Snippet snippet) {
    // Using PdfStamper to fill out the fields
    PdfReader reader = new PdfReader(snippet.getBytes());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfStamper stamper = new PdfStamper(reader, baos);
    stamper.setFormFlattening(true);
    AcroFields form = stamper.getAcroFields();
    // fill out the fields; you've already implemented this
    stamper.close();
    // return the template
    PdfReader reader = new PdfReader(baos.toByteArray());
    return w.getImportedPage(reader, 1);
}

There may be better solutions, for instance involving XFA, but I don't know if that's feasible as I don't know if the templates (the light blue part in my schema) are always the same. It would also involve creating new templates in the XML Forms Architecture.


问:
Passing multiple errors back from service layer
I am using Spring for a web application. To validate a user's input in a form such as for creating a Person entity I use JSR 303 validation to check for not null/empty or valid patterns etc.. Some things however I check in the service layer such as making sure a field is unique in the database and if not throwing an exception. I catch this exception in the controller and add an error to the field.

This is basically what Ben J is doing in Option 1 here https://stackoverflow.com/questions/3224749/passing-errors-back-to-the-view-from-the-service-layer

Service Layer

```<code>public Person createPerson(String username, String fullName, String specialCode)
        throws DuplicateUsernameException {
    // Check if username exists and throw exception otherwise create person.
    if (checkUsernameExists(username)) {
        throw new DuplicateUsernameException();
    }
    Person person = new Person(username, fullName, specialCode);
    return personDao.create(person);
}
</code>```

Controller

```<code>void createPerson(Form form, Errors errors) {

    try {
        service.createPerson(form.getUsername(), form.getFullName(),
                form.getSpecialCode());
    } catch (DuplicateUsernameException e) {
        errors.add("username", "This username exists");
    }

    // render view
    ...
}
</code>```

Up until now this has served me well but I now have a requirement to check two fields are individually unique and want to inform the user. In the above example if I wanted to check the specialCode was also unique I could add another check below the existing one in the service layer and throw a separate DuplicateSpecialCodeException.

Service Layer

```<code>public Person createPerson(String username, String fullName, String specialCode)
        throws DuplicateUsernameException, DuplicateSpecialCodeException {
    if (checkUsernameExists(username)) {
        throw new DuplicateUsernameException();
    }
    if (checkSpecialCodeExists(specialCode)) {
        throw new DuplicateSpecialCodeException();
    }
    Person person = new Person(username, fullName, specialCode);
    return personDao.create(person);
}
</code>```

Controller

```<code>void createPerson(Form form, Errors errors) {

    try {
        service.createPerson(form.getUsername(), form.getFullName(),
                form.getSpecialCode());
    } catch (DuplicateUsernameException e) {
        errors.add("username", "This username exists");
    } catch (DuplicateSpecialCodeException e) {
        errors.add("specialCode", "This special code exists");
    }

    // render view
    ...
}
</code>```

The problem is if the user submits a duplicate Username and a duplicate SpecialCode they will only be informed of the duplicate Username. I want to shown both fields.

What is a neat way of doing this?

My ideas so far are:

Throw an exception that contains all the errors.

Pass the Errors object to the service and add errors to this.

Both of these methods would rely on the service layer knowing about the name of the fields and a suitable error code which seems to go against keeping the layers separate.

答: In most languages, exceptions are classes that work just like any other class. You can add properties or methods to them. So why not allow a data structure or even another kind of error DTO or a list of error DTOs to be passed in the constructor of an UnableToCreatePersonException() ?  You could even define an interface like IMultipleErrorsException that some of your exceptions implement that has a method like getAllErrors() that returns the list of error DTOs. Each error DTO might have a key for a translation that contains an appropriate error message, and the Controller's responsibility then becomes ensuring that these messages get passed back to the user in the appropriate language.  Or the DTO could be a more sophisticated type that can handle the mapping from service layer exceptions to fields and error messages.</p>


问:
Why do we put private member functions in headers?
The answer to why we put private member variables in C++ headers is that the size of the class must be known at points where instances are declared so that the compiler can generate code that appropriately moves about the stack.

Why do we need to put private members in headers?

But is there any reason to declare private functions in the class definition?

The alternative would be essentially the pimpl idiom but without the superfluous indirection.

Is this language feature more than a historical error?

答:
It's to allow those functions to access the private members. Otherwise you'd need to friend them in the header anyway.

If any function could access the private members of the class then private would be useless.


答:
There are two reasons for doing this.

First, realize that the access specifier is for the compiler, and is not relevant at runtime. Accessing a private member outside of scope is a compile error.

Conciseness

Consider a function that is short, one or two lines. It exists to reduce the replication of code elsewhere, which also has the advantage of being able to change how an algorithm or whatever else works in one place instead of many (e.g. changing a sorting algorithm).

Would you rather have a quick one or two line in the header, or have the function prototype there plus an implementation somewhere? It is easier to find in the header, and for short functions, it is far more verbose to have a separate implementation.

There is another major advantage, which is...

Inline Functions

A private function may be able to be inlined, and this necessarily requires it to be in the header. Consider this:

```<code>class A {
  private:
    inline void myPrivateFunction() {
      ...
    }

  public:
    inline void somePublicFunction() {
      myPrivateFunction();
      ...
    }
};
</code>```

The private function may be able to be inlined along with the public function. That is done at the compiler's discretion, as the inline keyword is technically a suggestion, not a requirement.

Title: Why do we put private member functions in headers?

Body:
The answer to why we put private member variables in C++ headers is that the size of the class must be known at points where instances are declared so that the compiler can generate code that appropriately moves about the stack.

Why do we need to put private members in headers?

But is there any reason to declare private functions in the class definition?

The alternative would be essentially the pimpl idiom but without the superfluous indirection.

Is this language feature more than a historical error?

Body:
There are two reasons for doing this.

First, realize that the access specifier is for the compiler, and is not relevant at runtime. Accessing a private member outside of scope is a compile error.

Conciseness

Consider a function that is short, one or two lines. It exists to reduce the replication of code elsewhere, which also has the advantage of being able to change how an algorithm or whatever else works in one place instead of many (e.g. changing a sorting algorithm).

Would you rather have a quick one or two line in the header, or have the function prototype there plus an implementation somewhere? It is easier to find in the header, and for short functions, it is far more verbose to have a separate implementation.

There is another major advantage, which is...

Inline Functions

A private function may be able to be inlined, and this necessarily requires it to be in the header. Consider this:

class A {
  private:
    inline void myPrivateFunction() {
      ...
    }

  public:
    inline void somePublicFunction() {
      myPrivateFunction();
      ...
    }
};

The private function may be able to be inlined along with the public function. That is done at the compiler's discretion, as the inline keyword is technically a suggestion, not a requirement.


答:
If you allowed methods to be added to a class outside its definition, they could be added anywhere, in any file, by anyone.

That would immediately give all client code trivial access to private and protected data members.

Once you've finished the class definition, there's no way to mark some files as being specially blessed by the author to extend it - there are just flat translation units. So, the only reasonable way to tell the compiler that a particular set of methods are official, or blessed by the class author, is to declare them inside the class.

Note that we have direct access to memory in C++, which means it's generally trivial to create a shadow type with the same memory layout as your class, add my own methods (or just make all the data public), and reinterpret_cast. Or I can find the code of your private function, or disassemble it. Or lookup the function address in the symbol table and call or directly.

These access specifiers don't try to prevent these attacks, because that isn't possible. They only indicate how a class is supposed to be used.


答:
In Java, arrays are pseudo-objects. Object references can hold arrays, and they do have the standard Object methods, but they are very lightweight compared to a true collection. Arrays do just enough to meet the contract of an Object and use the default implementations of equals, hashCode, and toString quite deliberately.

Consider an Object[]. An element of this array can be anything that fits in an object, which includes another array. It could be a boxed primitive, a socket, anything. What does equality mean in that case? Well, it depends on what is actually in the array. That is not something known in the general case when the language was being designed. Equality is defined both by the array itself as well as its contents.

This is the reason why there is an Arrays helper class that has methods to compute equality (including deep equals), hash codes, etc. However, those methods are well-defined as far as what they do. If you need different functionality, write your own method to compare two arrays for equality based on the needs of your program.

While not strictly an answer to your question, I think it is relevant to say that you really should be using collections instead of arrays. Only convert to an array when interfacing with an API that requires arrays. Otherwise, collections offer better type safety, more well-defined contracts, and are generally easier to use than arrays.

Title: Why do arrays in Java not override equals()?

Body:
I was working with a HashSet the other day, which has this written in the spec:

[add()] adds the specified element e to this set if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2))

I was using char[] in the HashSet until I realized that, based on this contract, it was no better than an ArrayList! Since it's using the non-overridden .equals(), my arrays will only be checked for reference equality, which is not particularly useful. I know that Arrays.equals() exists, but that doesn't help when one is using collections such as HashSet.

So my question is, why would Java arrays not override equals?


问:
Why is time complexity of k-way merge sort O(nk^2)?
I'm comparatively new to algorithm analysis and am taking a related course on coursera where I came accross k way merge sort.

The time complexity of 2 way merge sort is n log2 n, of 3 way merge sort is n log3 n and of 4 way merge sort is n log4 n.

But, in the case of k-way the complexity is nk^2. This is because we pay attention to the merge part of the algo; (2n + 3n + 4n...kn).

But, in case of 2, 3 and 4-way algorithms, we pay attention to the recursive call of one function; (2T(n/2) + c.n).

Can anybody please explain why this is so? Or correct my approach to this question.

答:
the recursion depth is log n/log k,

merging costs n*log k, using a min heap for log k per element

thus we come at T(n) = n* log k + K* T(n/k) which (unless I'm mistaken) becomes n log n (actually n (c_1/k+log(n))= n/k + n*log(n) but the n/k becomes insignificant in big O)


答:
I'd say buying and selling are actions that do not define an object. You actually have a Person who can either buy or sell things; buying and selling would be interfaces:</p>

```<code>interface iBuyer
{
    void Buy();
}

interface iSeller
{
    void Sell();
}

public class Person: iSeller, iBuyer
{
    ...
}
</code>```

Title: Buyer vs Seller on UML Model

Body:
I'm modeling an Online Classified System where, naturally, who sells also can buy and vice-versa.

The question is: should I have two different Actors, Buyer and Seller or I could have, say, an actor Client capable either buy and sell?

How do you approach this Model?

Cheers,

Body:
I'd say buying and selling are actions that do not define an object. You actually have a Person who can either buy or sell things; buying and selling would be interfaces:

interface iBuyer
{
    void Buy();
}

interface iSeller
{
    void Sell();
}

public class Person: iSeller, iBuyer
{
    ...
}


答:
Well, the first event should be that a customer creates a shopping cart, so when the shopping cart is created you already have a customer id as part of the event.

If a state holds between two different events, by definition it is a valid state. So if you say that a valid shopping cart is associated to a customer, this means that you need to have the customer info when creating the cart itself

Title: Where should an object in CQRS+ES be fully initialized: in the constructor, or when applying the first event?

Body:
There appears to be widespread agreement in the OOP community that the class constructor should not leave an object partly or even fully uninitialized.

What do I mean by "initialization"? Roughly speaking, the atomic process that brings a newly created object into a state where all of its class invariants hold. It should be the first thing that happens to an object, (it should only run once per object,) and nothing should be permitted to get hold of an un-initialized object. (Thus the frequent advice to perform object initialization right in the class constructor. For the same reason, Initialize methods are often frowned upon, as these break apart the atomicity and make it possible to get hold of, and use, an object that is not yet in a well-defined state.)

Problem: When CQRS is combined with event sourcing (CQRS+ES), where all state changes of an object are caught in an ordered series of events (event stream), I am left wondering when an object actually reaches a fully-initialized state: At the end of the class constructor, or after the very first event has been applied to the object?

Note: I'm refraining from using the term "aggregate root". If you prefer, substitute it whenever you read "object".

Example for discussion: Assume that each object is uniquely identified by some opaque Id value (think GUID). An event stream representing that object's state changes can be identified in the event store by the same Id value: (Let's not worry about correct event order.)

interface IEventStore
{
    IEnumerable<IEvent> GetEventsOfObject(Id objectId);
}
```

<p>Assume further that there are two object types <code>Customer</code> and <code>ShoppingCart</code>. Let's focus on <code>ShoppingCart</code>: When created, shopping carts are empty and must be associated with exactly one customer. That last bit is a class invariant: A <code>ShoppingCart</code> object that is not associated to a <code>Customer</code> is in an invalid state.</p>

<p>In traditional OOP, one might model this in the constructor:</p>

<pre class="lang-cs prettyprint-override"><code>partial class ShoppingCart
{
    public Id Id { get; private set; }
    public Customer Customer { get; private set; }

    public ShoppingCart(Id id, Customer customer)
    {
        this.Id = id;
        this.Customer = customer;
    }
}
</code>```

I am however at a loss how to model this in CQRS+ES without ending up with deferred initialization. Since this simple bit of initialization is effectively a state change, wouldn't it have to be modelled as an event?:

partial class CreatedEmptyShoppingCart
{
    public ShoppingCartId { get; private set; }
    public CustomerId { get; private set; }
}
// Note: `ShoppingCartId` is not actually required, since that Id must be
// known in advance in order to fetch the event stream from the event store.
```

This would obviously have to be the very first event in any ShoppingCart object's event stream, and that object would only be initialized once the event were applied to it.

So if initialization becomes part of the event stream "playback" (which is a very generic process that would likely work the same, whether for a Customer object or a ShoppingCart object or any other object type for that matter)…

Should the constructor be parameter-less and do nothing, leaving all work to some void Apply(CreatedEmptyShoppingCart) method (which is much the same as the frowned-upon Initialize())?

Or should the constructor receive an event stream and play it back (which makes initialization atomic again, but means that each class' constructor contains the same generic "play back & apply" logic, i.e. unwanted code duplication)?

Or should there be both a traditional OOP constructor (as shown above) that properly initializes the object, and then all events but the first are void Apply(…)-ied to it?

I do not expect of answer to provide a fully working demo implementation; I'd already be very happy if someone could explain where my reasoning is flawed, or whether object initialization really is a "pain point" in most CQRS+ES implementations.


答:
Top programmers have a tendency to write very regular code that is easy to debug and understand, they utilize available tools (static analysis, compiler errors, debug code) to the max. Also, top programmers already learned the value of unit-testing through there own hard experience.

So while initial amount of problems per line is the same, the problems are weeded out faster.

Title: I am making 4-5x more story points than average, but producing bugs at half the rate. Graphs say it's 2x more bugs, how to deal with that?

Body:
So it is generally accepted that top tier programmers can produce an order of magnitude more/better code than their more average peers.

It's also generally accepted that the rate of errors made in code is relatively constant for programmers.

Instead, it tends to be impacted by the processes used when writing the code and after the code is written. (As I understand it) Humans tend to make mistakes at a fairly constant rate - better programmers just notice more of them and are quicker to fix them.

Note that both of above assertions come from Code Complete by Steve McConnell - so it's not a matter of differing perspectives.

So I've started to see this recently in my code. I can hammer out about 4-5x the amount of code as many of my peers (measured by story points estimated by the team), with higher quality (based on performance metrics and number of changes made after check-in). But I still make mistakes. Between better unit tests, a better understanding of what the code is doing, and a better eye for issues when doing code reviews I'm not producing 4-5x the number of bugs.

But I'm still producing about twice as many bugs found by QA as other developers on my team. As you might imagine, this causes some problems with non-technical folks doing metric measurements (read: my boss).

I've tried to point out that I'm producing bugs at half the rate of my peers (and fix twice as many), but it's a hard sell when there's graphs saying I produce twice as many bugs.

So, how to deal with the fact that increased productivity will lead to an increased number of bugs?


问:
How much functionality needed to create a new class?
Right now I am working on my own small project of a WPF file back up application. I have come to a point where I want to create a method that will copy files recursively from one place to another.

This is not the first time that I ask myself the question:

Should this method be a part of an existing class, or should I store it in a new class?

What bothers me the most is that if I create a new class, it will most likely consist of solely this method, so it seems like a stretch to create a whole new type for just one action. On the other hand, I believe it is a good abstraction. Copying files doesn't have much to do with a WPF window.

The example that I show here brings out a more general question. How to balance between functionality/abstraction/readability to create code where OOP principles don't obscure common sense? I am relatively new to programming, but I'd like to start following good coding practices as soon as possible, e.g. not implementing design patterns like crazy, because I have just read about them.

答:
The main principle and purpose of OOP is to combine your data with the logic that manipulates it.  Ergo, if your new method has functionality that has specifically to do with a class, then it belongs with that class.

If your  recursive copy requires you to store any state in memory, like a byte queue or something like that, then make a RecursiveCopy class, and put your Copy method there.  If your recursive copy method is stateless, then make it a static method, and put it in a static utility class.


问:
How is quality important to the programmer, the person?
I didn't ask how the quality of the software is important to the product itself, the customers/users, the manager or the company. I want to know how it is important to the programmer that build it.

I'll be interested in any books (please specify the chapter), articles, blog post, and of course your personal opinion on the subject regardless your experience.

答: quality code is a kindness to your future self</p>

ContentLicense: CC BY-SA 2.5


问:
Is using interfaces on internal code a good idea?
I'm working on a set of automated tests that we use internally at work. Lately, we've been designing classes that implement interfaces in addition to inheritance.

As I understand it, interfaces in Java are used to fulfill a contract. A class that implements an interface must include implementations of any members of that interface. This works really well for building libraries or objects that are meant to be used by outside teams or individuals since it guarantees certain methods will be present.

What about code that's entirely kept within a single team in a single location? (Assume this code will stay internal, or else this question changes entirely.) If I can simply go to my VCS history or ask a team-member about changes to code, do I really need to enforce these changes using interfaces? Even if a team is large, you could still develop conventions or tests to verify things. I feel like we're just making more work for ourselves by using interfaces, but maybe there are additional arguments.

NOTE: This project is a Java project and will stay that way. Interfaces here are instances of interface with all the syntax and rules that apply.

答:
Let's clarify a few things.

First, the primary purpose of an interface is to allow multiple implementations.  If there's only one implementation, you don't need an interface; the class already defines its own public API.  Some unit testing scenarios require interfaces, because a mock is an alternate implementation.

While an interface specifies an API, it doesn't necessarily specify a contract, per se.  Contracts have additional things in them like restrictions on parameter values, which interfaces lack.  An implementing class merely fulfills the interface's API.

While it's true that you are required to implement all of the members of an interface, that implementation could merely throw an UnsupportedOperationException.


答:
There was a design decision to make early on in Java:

Are arrays primitives? or are they Objects?

The answer is, neither really... or both if you look at it another way.  They work fairly closely with the system itself and the backend of the jvm.

One example of this is the java.lang.System.arraycopy() method which needs to take an array of any type.  Thus, the array needs to be able to inherit something and thats an Object.  And arraycopy is a native method.

Arrays are also funny in that they can hold primitives (int, char, double, etc... while the other collections can only hold Objects.  Look, for example, at java.util.Arrays and the ugly of the equals methods.  This was put in as an after thought.  deepEquals(Object[], Object[]) wasn't added until 1.5 while the rest of the Arrays class was added in 1.2.

Because these objects are arrays, they let you do some things that are at the memory or near memory level - something that Java often hides from the coder.  This allows certain things to be done faster at the expense of mostly breaking the object model.

There was a trade off early in the system between flexibility and some performance.  Performance won out and the lack of flexibility was wrapped in the various collections.  Arrays in Java are a thinly implemented Object on top of a primitive type (originally) intended for working with the system when you need it.

For the most part, raw arrays were things that it appears that the original designers tried to ignore and tuck away only in the system.  And they wanted it to be fast (early Java had some issues with speed).  It was a wart on the design that arrays aren't nice Arrays, but its one that was needed when you wanted to expose something as close to the system as possible.  For that matter, the contemporary languages of early Java also have this wart - one can't do a .equals() on C++'s array.

Java and C++ both took the same path for arrays - an external library that does the operations as needed on arrays rather than Arrays... and suggesting the coders to use better, native types unless they really know what they are doing and why they are doing it that way.

Thus, the approach implanting .equals in an array is wrong, but its the same wrong that coders coming from C++ knew of.  So chose the least wrong thing in terms of the performance - leave it as the implementation of Object: two Objects are equal if and only if they are referring to the same object.

You need the array to be a primitive like structure for being able to communicate with native bindings - something as close to the classic C array as possible.  But unlike the other primitives, you need the array to be able to be passed as a reference, and thus an Object.  So its more of a primitive with some Object hacks on the side and some bounds checking.


答:
The main point of an interface is not to hide things so that evil contract programmers cannot exploit things they haven't paid for. It's to simplify the conceptual task of dealing with a module.

Knowing only the minimum about a class that is necessary for using its services is good. If the class exposed more detail than is necessary, the user will inevitably add this to their mental model of the class, and since memory, attention etc. are finite, this is wasted effort that might be lacking in other, more important places.

All this applies to other programmers just as much as to your own team or even to yourself. Using a class you yourself have written without knowing details of its implementation is  very good sign. It shows that you have successfully solved a task once and once only, and moved on to other, higher-level tasks. Interfaces are a valuable tool for achieving this (among other things, such as e.g. multiple implementations), therefore the reasons for using them have nothing to do with how many developers or what kind of team interact with a class.

Title: Is using interfaces on internal code a good idea?

Body:
I'm working on a set of automated tests that we use internally at work. Lately, we've been designing classes that implement interfaces in addition to inheritance.

As I understand it, interfaces in Java are used to fulfill a contract. A class that implements an interface must include implementations of any members of that interface. This works really well for building libraries or objects that are meant to be used by outside teams or individuals since it guarantees certain methods will be present.

What about code that's entirely kept within a single team in a single location? (Assume this code will stay internal, or else this question changes entirely.) If I can simply go to my VCS history or ask a team-member about changes to code, do I really need to enforce these changes using interfaces? Even if a team is large, you could still develop conventions or tests to verify things. I feel like we're just making more work for ourselves by using interfaces, but maybe there are additional arguments.

NOTE: This project is a Java project and will stay that way. Interfaces here are instances of interface with all the syntax and rules that apply.


答:
Spend some of that extra time cleaning, polishing, and testing your code. There will still be mistakes, but there will be less. That takes time. Your code output rate will go down, but your bug-free code output will increase, and that will result in better productivity. Because bugs are expensive.

Can you keep your code in a branch or a test environment until you kick it around and catch more of the bugs? Bugs in a branch generally cause less waves than bugs in production code.

But I'm not exactly digging your asserts leading into your question. And perhaps your boss isn't either.

I don't think that every coder produces the same rate of errors. Your second link is actually entirely off topic as it's comparing different languages, not different coder skill levels. Code complete mentions some large-sample measurements that are looking at the process rather than the skill of the coders. And when they say that top-tier coders produce more/better code, part of that means that it has less bugs. Depends on the application. So, yeah, I think it IS a matter of differing perspective.

In the end though, if the boss wants cleaner code, give him cleaner code.


答:
In general, my preference is to base the design on polling at fairly low frequency, but then to use events to trigger early scans.

The good thing about events is responsiveness.

There are a few bad things about them:

They can happen more often than you want, as for example there may be 10 events in a row, early ones being overridden by later ones, and the program gets jerked around trying to track every little change. This is the "short leash" problem. If there are two bodies of information, that need to be kept in agreement, I typically use a routine to scan for disagreements and patch them up, rather than count on events or notifications.

Events can be dropped or duplicated, so if it is important to keep track of changes, they can lead to errors. This is the "why wasn't I told?" or "did you already tell me that?" problem.

It is easy to create event handlers, so easy that it is easy to create more than you want. This can lead to things like slow window painting because it's being done many times when it only needed to be done once. Then when you remove an event handler, you may think you've turned off the event handling, but you haven't, because you haven't removed all of them. This is the "spam" problem.

So as I said, I prefer to minimize event handling (and its cousins - notifications and nested properties), but to definitely employ them, sparingly, where their benefits will do the most good.

Title: Polling vs events pros and cons in JavaScript

Body:
I'm bit of a novice to JavaScript so I've been wondering on positive and negative sides of using polling compared to using events in JavaScript? When does one use one or the other?

By polling I consider any effect that is triggered on something that repeats itself usually using setTimeout. But also for example:

```<code>function render() {
   Bloop.renderComponent(box, document.body);
   requestAnimationFrame(render);
}
</code>```

Is also polling since requestAnimationFrame(render) which is called before each frame is called.

Basically anything that fits this definition


问:
What's the first thing you write when trying out a new language?
I think everyone has their own program or set of features beyond "Hello World!", that they use when trying out a new language.

Mine is a guessing game:

```<code>I'm thinking of a number 1-10, guess what it is!
Guess: 3
Nope, too low!
Guess: 7
Nope, too high!
Guess: 5
Yes, You win!
Play again (Y/N)? N
</code>```

What do you write?

答: followed by a very simple prime number generator, then whatever is on my mind at the time.</p>


答: This depends on the programmer. I have met plenty of sloppy ones, who get sexual release from "getting it done". There are many ways to look at this. Sometimes you do want to write a throw-away Python script. Sometimes you dig a huge hole by doing wrong things. If you work for NASA or other mission-critical places, then quality is inversely proportional to the number of people that will die. Sometimes revenue generation is key to the survival of a start-up. http://www.codinghorror.com/blog/2009/02/paying-down-your-technical-debt.html Jeff Attwoods and Joel Spolsky see refactoring differently.</p>

Title: How is quality important to the programmer, the person?

Body:
I didn't ask how the quality of the software is important to the product itself, the customers/users, the manager or the company. I want to know how it is important to the programmer that build it.

I'll be interested in any books (please specify the chapter), articles, blog post, and of course your personal opinion on the subject regardless your experience.


问:
Using commit messages for time tracking
Some products can parse a special syntax in commit messages to extract additional data, such at time tracking information: https://confluence.atlassian.com/display/FISHEYE/Using+smart+commits

To me, this seems like the misuse of one tool to activate a feature on another, but I'm having trouble articulating my reasoning. It seems similar to the process smell of storing issue tracking information in code comments.

Is there anything fundamentally wrong with using commit messages as a time tracking mechanism?

答:
I don't see anything wrong with it, as long as it doesn't obscure the original purpose of commit messages - saying what the change is about. If you use those tools, why would you have anything against them being better integrated with each other?

If you get your CI integrated with the repository, so you can follow a single link from a broken build to the changelist that caused it, and from there to the issue ticket and code reviews of the change, it's simply a convenient shortcut for stuff you'd have to look up yourself anyway. I think we can agree on that.

This feature just takes it a step further. And while I wouldn't care that much for time tracking - it's not like it takes that much time to do it manually - creating or updating a review with a single line would be great.

Title: Using commit messages for time tracking


问:
How do you let a user choose the app database location?
Writing software for a client, and one of their requirements was that the user be able to specify where the application database is stored, be it on the local network or in an online repository.

I can let them choose where to put it, but how do I store that information in the application?

I guess I don't understand how to persist changes in an application that is already deployed. This is my first piece of software, so I've never been through the deployment process. Written in C# for Windows.

答: For something like a target path, just use Application.Settings to persist it.</p>


答:
The situation is that you work four times as fast as the average programmer, but you make twice as many mistakes in a given amount of time. Relative to the amount of work you do, you actually make HALF as many mistakes as "average."

You might try to point out your low mistakes to work ratio, or even mistakes to completed product (which you can complete in one-fourth the normal time). Most bosses will accept that.

There are a few bosses that won't because they work with an "allowance" mindset of mistakes per time. Then you might slow down your work pace, doing TWICE as much work as average within a given time, and make the same (or fewer) mistakes because you have more time to check your work.


问:
Theoretically bug-free programs
I have read lot of articles which state that code can't be bug-free, and they are talking about these theorems:

Halting problem

Gödel's incompleteness theorem

Rice's theorem

Actually Rice's theorem looks like an implication of the halting problem
and the halting problem is in close relationship with Gödel's incompleteness theorem.

Does this imply that every program will have at least one unintended behavior?
Or does it mean that it's not possible to write code to verify it?
What about recursive checking? Let's assume that I have two programs. Both of them have bugs, but they don't share the same bug. What will happen if I run them concurrently?

And of course most of discussions talked about Turing machines. What about linear-bounded automation (real computers)?

答:
It's not so much that programs can't be bug-free; it's that it's very hard to prove that they are, if the program you're trying to prove is non-trivial.

Not for lack of trying, mind you.  Type systems are supposed to provide some assurance; Haskell has a highly-sophisticated type system that does this, to a degree.  But you can never remove all of the uncertainty.

Consider the following function:

```<code>int add(int a, int b) { return a + b; }
</code>```

What might go wrong with this function?  I already know what you're thinking.  Let's say that we've covered all of the bases, like checking for overflow, etc.  What happens if a cosmic ray strikes the processor, causing it to execute

```<code>LaunchMissiles();
</code>```

instead?

OK, maybe that's a bit contrived.  But  even simple functions like the add function above must operate in environments where the processor is constantly changing contexts, switching between multiple threads and cores.  In an environment like that, anything can happen. If you doubt this, then consider that RAM is reliable, not because it is error free, but because it has a built-in system to correct the bit errors that inevitably occur.

I know what you're thinking.  "But I'm talking about software, not hardware."

There are many techniques that can improve your confidence level that the software works the way it is supposed to.  Functional programming is one of them.  Functional programming allows you to better reason about concurrency.  But functional programming is not a proof, any more than unit tests are.

Why?  Because you have these things called edge cases.

And once you get only a little beyond the simplicity of return a + b, it becomes remarkably difficult to prove a program's correctness.

Further Reading

They Write the Right Stuff

The Ariane 5 Explosion

Title: Theoretically bug-free programs

Body:
It's not so much that programs can't be bug-free; it's that it's very hard to prove that they are, if the program you're trying to prove is non-trivial.

Not for lack of trying, mind you.  Type systems are supposed to provide some assurance; Haskell has a highly-sophisticated type system that does this, to a degree.  But you can never remove all of the uncertainty.

Consider the following function:

int add(int a, int b) { return a + b; }

What might go wrong with this function?  I already know what you're thinking.  Let's say that we've covered all of the bases, like checking for overflow, etc.  What happens if a cosmic ray strikes the processor, causing it to execute

LaunchMissiles();

instead?

OK, maybe that's a bit contrived.  But  even simple functions like the add function above must operate in environments where the processor is constantly changing contexts, switching between multiple threads and cores.  In an environment like that, anything can happen. If you doubt this, then consider that RAM is reliable, not because it is error free, but because it has a built-in system to correct the bit errors that inevitably occur.

I know what you're thinking.  "But I'm talking about software, not hardware."

There are many techniques that can improve your confidence level that the software works the way it is supposed to.  Functional programming is one of them.  Functional programming allows you to better reason about concurrency.  But functional programming is not a proof, any more than unit tests are.

Why?  Because you have these things called edge cases.

And once you get only a little beyond the simplicity of return a + b, it becomes remarkably difficult to prove a program's correctness.

Further Reading

They Write the Right Stuff

The Ariane 5 Explosion


答:
Private member functions may be virtual, and in common implementations of C++ (that use a vtable) the specific order and number of virtual functions is required to be known by all clients of the class. This applies even if one or more of the virtual member functions is private.

It might seem that this is like "putting the cart before the horse", because compiler implementation choices shouldn't affect the language specification. However, in reality the C++ language itself was developed at the same time as a working implementation (Cfront), which used vtables.


问:
How to break up Yocto layers for continuous integration?
We are building embedded software using a Linux setup based on the Yocto project.  We have a couple different configurations that we are building for different purposes (but the same target).

I have been struggling with the best way to set up continuous integration for this project.  Ideally, I would like to be able to reuse most of the artifacts, so that someone working on a specific layer can get rapid feedback.

However, I haven't found any good suggestions on a way to break these builds apart.  Is there a way to separate the various layers we are working on into multiple builds with shared artifacts so that it takes a couple hours for developers to get feedback from each build?

答:
We don't test individual layers. We build and test the entire yocto code base we use.

We have a build script that accepts some arguments:

release, "stable" or latest git HEAD

include ptests or not

include developer tools or not

architecture to build for (e.g. qemu, x86, x86_64)

Now we have multiple builds in our build system:

If build against the latest git HEAD we do not do a clean build and just update the meta* layers (rsync -a --delete). Sometimes we have to wipe the folder of this build. These are quick builds.

If we do a "release" build, we do a clean build

If we do a "stable" build, we do a clean build

Create additional builds as needed (e.g. with ptest or developer tools).

The build script allows us also to copy the downloaded files on releases or define to have a 'no network' build which gets the source files from a folder.

Regarding automated testing we are not that far yet (can't run qemu on the build VM). But the ptest is a good start and we want to automate that in the future. Yocto itself does also provide some options here, but I didn't look into them yet.

Regarding ptests there are some open issues of missing dependencies (like perl ptest), therefore we created an indivual ptest-execution script that only tests packages with the name xy- (where xy is our company shortcut, all packages from us are separated this way). There is also an additional package that only contains ptests for software from public openembedded and yocto layers we want to test.


问:
Languages on a resume: Is it better to put "C/C++" or "C, C++"?
I'm graduating in a couple of weeks, and my resume (as expected) lists the languages that I've had experience with. Previously I've put "C/C++", however back then I didn't have that much experience with these two languages as I do now.

Now that I've formally learned these two languages, it has become evident to me (and anyone who really knows these languages) that they are similar, and completely disimilar at the same time. Sure, most C code is compilable C++ code, but syntax and incorporation of library functions is pretty much where these similarities end. In most non-trivial problems, chances are that the desirable C++ solution will be different from the desirable C solution.

My question:

Will recruiters take note or care about whether you put "C/C++" as opposed to "C, C++"? Will they assume a lack of knowledge of the workings of either because of the inclusion of the first form, or perhaps see the inclusion of the second form as a potential "resume beefer" (listing them as 2 languages, instead of "one")?

Furthermore, for jobs that you've applied to that were particularly interested in these two langauges, did the interview process include questions about the differences between C programming and C++ programming (so, about actual programming techniques, not only the extra paradigms in the latter)?

答:
I'm sorry, but don't you think this is is really splitting hairs? When I am hiring a programmer I just take a brief look at what the language listing is because I am usually hiring for a specific language anyway. Also, just because you know a language doesn't mean that you really know all of its libraries, API's, and know how to use them.

What I am more interested in is usually the work experience or any projects that you might have worked on. I know lots of languages but I have only done serious work in about two or three of them. I would spend more time highlighting your successes and experience rather than how many languages you know. Just my $.02.


问:
I am making 4-5x more story points than average, but producing bugs at half the rate. Graphs say it's 2x more bugs, how to deal with that?
So it is generally accepted that top tier programmers can produce an order of magnitude more/better code than their more average peers.

It's also generally accepted that the rate of errors made in code is relatively constant for programmers.

Instead, it tends to be impacted by the processes used when writing the code and after the code is written. (As I understand it) Humans tend to make mistakes at a fairly constant rate - better programmers just notice more of them and are quicker to fix them.

Note that both of above assertions come from Code Complete by Steve McConnell - so it's not a matter of differing perspectives.

So I've started to see this recently in my code. I can hammer out about 4-5x the amount of code as many of my peers (measured by story points estimated by the team), with higher quality (based on performance metrics and number of changes made after check-in). But I still make mistakes. Between better unit tests, a better understanding of what the code is doing, and a better eye for issues when doing code reviews I'm not producing 4-5x the number of bugs.

But I'm still producing about twice as many bugs found by QA as other developers on my team. As you might imagine, this causes some problems with non-technical folks doing metric measurements (read: my boss).

I've tried to point out that I'm producing bugs at half the rate of my peers (and fix twice as many), but it's a hard sell when there's graphs saying I produce twice as many bugs.

So, how to deal with the fact that increased productivity will lead to an increased number of bugs?

答:
Assuming you would produce the same "amount" of code like your colleagues in 20% of their time, you could spend 4 times as much on really debugging the code and making it perfect, which would reduce your bug rate even more. Then you could call yourself a good programmer.

The biggest question is why you are coding 5 times as much as the others instead of aiming for quality. Is this something your ego dictates you or does your boss force you?

Also you need to consider costs for fixing a bug. When you find it early it you might still be "inside" the code enough to fix it quickly. If it appears only after another month of development, it could be hard to find or even force you to change big parts of the already programmed code.

You seem to have the skillset to produce code, and you could make it awesome if you put your focus on quality instead of speed. Try it a while, my guess is you will like it.

The next problem then is to get the acknowledgement (speak money) for your better performance. Talk to your boss and ask him how to proceed, it is his company and money after all, and if he wants you to produce less bugs, he should also decide in which way it happens.


答:
I'll go out on a limb and be the devil's advocate.  That's not to say I don't sympathise with your plight but, well, my sympathy won't help you.  So allow me to add to Philip's perspective:

Your boss cares about the quality of the product, partly because his or her name and reputation will be tied to it.  Part of the quality is the perceived amount of bugs.  If you sell an awesome drill that drills four times faster than any competing drills, but also breaks down twice as often, you'll have a bad reputation.  Even if it's arguable that the drill performs better, people get used to the speed, but they'll remember the breakdowns.

In hindsight, most bugs are obviously preventable.  If only you were a little more careful, your boss will feel, you could avoid these issues and any necessary clean-up.  From his perspective, that's a trivial, sensical thing to ask, and any arguing you do about it is both not going to work and is going to make you look bad.

He can't measure your superior productivity.  You claim higher productivity based on a verifiable metric, so how do your colleagues feel about it?  Do they agree, perhaps grudgingly, that you are a more productive programmer, or are you alone in your opinion?  You'll make a stronger point if you have other people to back up your assertions.

That's for perspective.  Now, how do you go about 'fixing' this frustrating situation you are in?

Do slow down a bit.  Mention explicitly to whoever distributes tasks that you're going to try to lower the bug rate (*), so that they're not surprised by your lower intake.  If anything, slowing down will reduce the number of bugs assigned to you out of sheer lack of supply.

(*) There's a difference between, on the one hand, acknowledging that there are bugs to your name and that you'll try to lessen that amount and, on the other hand, admitting that you have too many bugs to your name and should take action.

Don't try to convince your boss, because it won't work.  Again, that doesn't mean you have to concede your point; you can present a counterpoint and hold your opinion without dismissing his concerns.  Because if you do argue the point and cannot satisfactorily prove your superior productivity (and even if you can), you're going to risk insulting your colleagues, or appearing dismissive of them.  You don't want to be that guy.


问:
How other thread can show the incremented value unless the 1st thread reaches the return statement?
My code is given below.

In the for loop I am getting unexpected output i.e.

before completing the execution of for loop by 1st thread the 2nd thread comes in for loop and shows incremented value.

```<code>public class ThreadSafe {
    public static void main(String[] args) throws InterruptedException {
        System.out.println("main()");

        B b=new B("1st Thread");
        B b1=new B("2nd Thread");
        B b2=new B("3rd Thread");
        b.start();
        b1.start();
        b2.start();
    }
}

class MyCounter {
    private static int count;

    public static int getCount(){
        for(int m=0;m<2;m++){
            System.out.println(count+" "+Thread.currentThread().getName());
        }

        return count++;
    }
}

class B extends Thread{
    public B(String tname) {
        super(tname);
    }

public void run() {
    MyCounter.getCount();
    }
}
</code>```

The question is when 1st thread executes for loop then other threads executing return statement is this the reason of showing increment value or something else?

How other thread can show the incremented value unless the 1st thread reaches the return statement?

答:
Example output:

```<code>0 1st Thread
1 3rd Thread
1 3rd Thread
2 1st Thread
0 2nd Thread
0 2nd Thread
</code>```

What you're seeing here is that your threads have locally cached your count variable, as it is not declared as being volatile:

When applied to a field, the Java volatile guarantees that:

(In all versions of Java) There is a global ordering on the reads and writes to a volatile variable. This implies that every thread accessing a volatile field will read its current value before continuing, instead of (potentially) using a cached value.

(emphasis mine)

Being volatile won't save your counter from misbehaving under ++ though, as it is not an atomic operation:

[That] an increment expression, such as counter++, does not describe an atomic action. Even very simple expressions can define complex actions that can decompose into other actions[...]  Atomic actions cannot be interleaved, so they can be used without fear of thread interference.

The Java tutorial on concurrency is a great place to learn about these things.

Body:
Example output:

0 1st Thread
1 3rd Thread
1 3rd Thread
2 1st Thread
0 2nd Thread
0 2nd Thread

What you're seeing here is that your threads have locally cached your count variable, as it is not declared as being volatile:

When applied to a field, the Java volatile guarantees that:

(In all versions of Java) There is a global ordering on the reads and writes to a volatile variable. This implies that every thread accessing a volatile field will read its current value before continuing, instead of (potentially) using a cached value.

(emphasis mine)

Being volatile won't save your counter from misbehaving under ++ though, as it is not an atomic operation:

[That] an increment expression, such as counter++, does not describe an atomic action. Even very simple expressions can define complex actions that can decompose into other actions[...]  Atomic actions cannot be interleaved, so they can be used without fear of thread interference.

The Java tutorial on concurrency is a great place to learn about these things.


问:
Coding: conciseness/efficiency vs readability
I am fairly new to c# and trying to learn best practices. I've been faced with many situations over the last week in which I need to make a choice between longer+simpler code, or shorter code that combines several actions into a single statement. What are some standards you veteran coders use when trying to write clear, concise code? Here is an example of code I'm writing with two options. Which is preferable?

A)

```<code>    if (ncPointType.StartsWith("A"))//analog points
    {
        string[] precisionString = Regex.Split(unitsParam.Last(), ", ");
        precision = int.Parse(precisionString[1]);
    }
    else
    {
        precision = null;
    }
</code>```

B)

```<code>    if (ncPointType.StartsWith("A"))//analog points
        precision = int.Parse(Regex.Split(unitsParam.Last(), ", ")[1]);
    else
        precision = null;
</code>```

C)

```<code>    precision = ncPointType.StartsWith("A") == true ?
            int.Parse(Regex.Split(unitsParam.Last(), ", ")[1]) :
            null;
</code>```

答:
From Clean Code:

Each line represents an expression or a clause, and each group of lines represents a complete thought. Those thoughts should be separated from each other with blank lines.

I also find that ternary operators can be unreadable if the lines are too long; so I would go with B.

However, also from Clean Code, I would split out the conditional into it's own method.

It only takes a few seconds of thought to explain most of your intent in code. In many cases it's simply a matter of creating a function that says the same thing as the comment you want to write.

Consider, which is more readable, this:

```<code>if (ncPointType.StartsWith("A"))//analog points
    precision = int.Parse(Regex.Split(unitsParam.Last(), ", ")[1]);
else
    precision = null;
</code>```

or this:

```<code>if (isAnalog(ncPointType))
    precision = int.Parse(Regex.Split(unitsParam.Last(), ", ")[1]);
else
    precision = null;
</code>```

Body:
From Clean Code:

Each line represents an expression or a clause, and each group of lines represents a complete thought. Those thoughts should be separated from each other with blank lines.

I also find that ternary operators can be unreadable if the lines are too long; so I would go with B.

However, also from Clean Code, I would split out the conditional into it's own method.

It only takes a few seconds of thought to explain most of your intent in code. In many cases it's simply a matter of creating a function that says the same thing as the comment you want to write.

Consider, which is more readable, this:

if (ncPointType.StartsWith("A"))//analog points
    precision = int.Parse(Regex.Split(unitsParam.Last(), ", ")[1]);
else
    precision = null;

or this:

if (isAnalog(ncPointType))
    precision = int.Parse(Regex.Split(unitsParam.Last(), ", ")[1]);
else
    precision = null;


问:
When to add new project to solution?
I'm tidying up my company's Version Control Guidelines.  One of my tasks is to determine how solutions should be organized in a very broad sense.

I have somewhat come to my own conclusion that one broad requirement to document is that, for the most part, CSProj/VBProj projects should live on their own all at the same level in a branch.

However, there are a measureable number of projects that aren't independent, and are tightly coupled to another.  For instance, a Unit Testing project has no business by itself since it only exists in support of one other project.  So it can (and should) be directly added to a solution with the project it supports.  Same with an individual UI who's sole existence is to test one project.  Or an implementation test project... and probably similar examples.

So my goal is to mandate, in a way, that projects should not be added directly to a solution except in such examples.

Disclaimer I'm not saying that one application cannot have a solution with multiple projects having been "Add Existing Project" to the solution.  But in those cases, each of those projects should be addable/removable because they exist all at the same level of a namespace or folder organization.

This would be easiest if there was some documentation I could find with a history of better wording.  But any searches I do just end up with How-To tutorials to add projects to a solution.  There are no Best Practies that get into this.

答:
Hmm, trying to mandate how to factor a solution into projects is sort of like mandating how to factor a problem domain into objects in OOP. Good developers know how to do it. Bad developers don't. It is a bit of an art, and an acquired skill, yet is subjective enough that I would avoid mandating too much. I may have 6 different developers who are all bright and experienced and they may factor a solution into projects differently. Everytime someone in one of my clients sets out to create a guideline, it seems that it is all the buzz or a week, then developers go back to doing what they do, and forget about the guidelines.

That said, I don't mean to say it is a useless effort. I think it is assumed that you will factor the individual layers of a particular architecture (such as a Database Drive MVC Web Application) into projects that make sense (like Domain, Data Access, Service Layer, Web Layer, Test Project), but beyond that, you have to ask yourself:

What defines reusable? If it is reusable, with a distinct subject
matter, factor it out. If you can envision an appopriate name for
the assembly / dll that describes the assembly's subject matter or
use, then it is a candidate for a project.

If you can't envision a name for it, besides "Common" or "Tools", then possibly it still belongs in a separate project, but possibly a common shared project for stuff that doesn't fit, but is still reusable. Combine it into an existing common project with the same level of (or lack of) dependencies.

Is it something you can assign to an individual developer? An artifact that you can turn into a robust, reusable library, and even eventually stabilize it so that you don't rebuilt it on the same schedule as your solution? It is a project, at least.

What is maintainable? Too many projects can get out of hand and become a mental or visual burden. If I find myself forgetting where something is, it is probably not in the right place. If I find myself with a screen full of collapsed project nodes, the visual load may also be a bit high for productivity, but not always. Larger, more complex solutions tend to have higher mental and visual load.

At the very least, every project should have a README.txt with a description of what it is.

A certain level of project "factoring" is good to keep a wide, shallow structure. Just like it is bad practice to write HUGE methods or classes, it is bad practice to write HUGE projects. But how can you mandate this, unless all your solutions are the same size and complexity?

Also avoid trying to find a problem for the solution, and instead, make sure there is really a problem, before mandating a solution. Instead, focus on enabling developers to be more productive with automation, productivity tools, simplified company policies, reduced paperwork requirements (cut out redundant time-keeping, etc.) and those things may help as much as the guideline.

When you hire good people, they figure it out anyway. Make sure you really have good people. Processes never fix bad people, but processes do hinder good people.

Title: When to add new project to solution?


问:
Helping someone who is not and never will be a professional programmer write code that is more legible and usable to use and interpret
I am Elvis, trying very hard to learn to be Einstein. I work for Mort.

What the hell is this crazy idiot talking about!?!? (You only need to read the first few paragraphs)

If you don't feel like reading that link, basically, I am a professional programmer, and my boss is (this is scarily accurate):

the professional line-of-business programmer who lacks a degree in computer science but has a great deal of familiarity with Office and VBA, and who typically writes productivity applications shared amongst his coworkers

All that said, a large portion of my job is taking his cobbled together code and making it production ready. However, the very poor style and cargo-cultism makes this difficult. This is compounded by the fact that he is unwilling to read programming books or allow me to help him refactor his code.

Are there some other strategies for helping someone who is not a professional programmer, never will be a professional programmer write code going forward that is more legible and usable for me to use and interpret?

答:
You've got to ask yourself: what is your ultimate goal here?
1. to help your boss?
2. to help the company?
3. to help yourself?
And before you answer "all of the above", slow down. Your first task is to clearly define your primary objective, because the answer depends on it.

If you goal is to:

Help your boss? Give It Up. He doesn't appear to be asking for it. You said, "He knows his code is bad, but it does what he needs." Well then, end of discussion. Unless and until your boss is dissatisfied with the current situation, he is not going to change, and he will resent your efforts to help him. If at some point in the future he does "feel the pain" of the status quo, hopefully you will have established yourself as a trustworthy mentor and he will know where to come for help.

Help  your company? Is the current situation threatening the bottom line? Are deadlines at risk? Is upper management increasing its heat? If not, then Give It Up. (This is essentially the point that Jimmy Hoffa made in his comment to your original post.) If, however, the current situation does in fact represent an unacceptable risk to your department/company, then a change of process is in order. In that case I would suggest that you sit down and outline a different division of labor. The key here is to explain that the time you spend refactoring your boss' code would be better spent writing new code. You say you don't have time writing it all yourself, but that's not what I'm suggesting. You need to figure out how to maximize your respective strengths. Stop thinking of him as a Mort, and  think of him as a junior developer with superior domain knowledge. That is a very common working arrangement in the industry, and it would behoove you to learn how to thrive in it.  For example, make sure that he knows that you know how essential his expertise is (repeat this step often), and then humbly suggest the following strategy (or something similar) as a quicker path to get his knowledge to the market: (a) break the work into "agile" sprints, (b) collaborate heavily up-front (in each sprint) defining the over-all requirements and architecture. (c) Let him go off and build the prototype to work out all the algorithmic decisions, while you build the infrastructure that you agreed upon in previous step. (d) Implement his algorithms into your structure while he builds tests to verify it. (e) Conduct your V&V together in a peer-programming environment. (e.g., "This test failed; why? algorithmic logic error or coding mistake?"; iterate here).

Help yourself? Be honest here. If all you are doing is complaining that you don't enjoy your job, I suggest you need to spend more time thinking about #2 above. If you don't care about the company AND you don't enjoy your job, start distributing your resume. If you DO care about your company but don't enjoy your job, then focusing on #2 should help on BOTH accounts. But in that case, it is a "win-win" only if it is clear to everyone that your passion genuinely stems from a desire to Help The Team, and not just from a self-centered frustration in your assignment.

ContentLicense: CC BY-SA 4.0