答:
Using strategy objects in the described way is a good start to simplify your PointBase class, I would not hesitate to introduce them even if they do not solve your problem with the BreakEven property.

For allowing custom properties, you could provide some kind "extension mechanism" in your PointBase class (which I would rename to Point after the redesign). In the most simple form, this could be just a list of custom properties for each Point object, together with a list of their values (and the list is empty by default). This might boil down to some kind of EAV model. EAV is sometimes seen as an anti-pattern, but for this specific case its usage is fine as long as you do not use it for the majority of properties, only for your "special custom properties".

See also this former question on "Programmers" about custom fields. In my answer there, I mentioned Martin Fowler's book "Analysis Patterns" - I am pretty sure it will help you for your problem, since it contains a very extensive discussion how to model measurements and observations, including (custom) properties and similar things.

Title: How can I add properties to subclasses and access them without casting from a superclass?

Body:
I'm trying to model a multi-dimensional point class in C#. I have about eight different types of points, and there may be more in the future. Right now, I have a superclass (PointBase) that holds all the common behaviors and data. This data includes only simple properties like doubles, strings, enums, and DateTimes (these are the dimensions). The subclasses (let's say 1Point, 2Point, etc.) all override at least things: the methods that have behavior for calculating two of these dimensions. If this behavior were the only changing thing, I could just use the Strategy + Factory pattern and be done with it (and honestly, I probably will refactor those two simple common behaviors out later).

Unfortunately, I'm stuck because some points add a property or two based on their type, or based on values of other properties in the superclass. For example, for point types 1-7, I don't need an additional Breakeven property, but for type 8, I do (this is problem #1).

In addition (this is problem #2), depending on the Product property (which exists and is set in the superclass, and is an enum), I may need to add a Term enum property that would apply to all subclass points. However, only one of my Product enum values needs a term. The others don't.

This situation is complicated by needing to store lists of these points in a List<PointBase> data structure that hides additional public properties. I'd have to cast each PointBase to a 1Point or 2Point or whatever when I took it out, and this (of course) breaks some design principles (separation, at the very least, I think).

Unfortunately, I'm also trying to display these different points on the same WPF DataGrid (in a scheme where the user can select 1Point or 2Point or whatever, and get the points' public properties displayed in the DataGrid). Although all of this code so far is contained within my model  (in a separate DLL), I'm also unsure of how to represent this polymorphism in my view in a DataGrid. I'm totally fine with allowing the DataGrid to just autogenerate columns based on the points' public properties, but again, passing these points around in a List<PointBase> means that there's no way to get at those additional properties I need to add. I thought of instead adding a virtual Dictionary to the superclass called CustomAttributes to which I would add a string key and string value every time I needed to include some additional properties. But this is very annoying, because flattening a Dictionary for a DataGrid is really hard. I'm worried that this is the only way though...

From what I know (which is limited w.r.t. software engineering), I need something like an abstract factory to capture all this polymorpism. But I'm not exactly sure. To recap, I need:

The ability to add public properties to certain subclasses based on their type. For example, for the 8Point subclass, I need to add a Breakeven property, but this property doesn't make sense for other subclasses.

The ability to add public properties to all subclasses based on values of properties in the superclass. For example, if the Product (set in the superclass) is A, I need an additional property added to all subclasses called Term. This property does not apply or make sense for any other products.

I'm not married to inheritance here (in fact, I'd like to do something more elegant/simpler if possible, such as delegation + interfaces), so I'm open to any solutions. Thank you in advance!

EDIT: To give some more context, here is what my setup looks like right now:

```<code>public abstract class StatisticPointBase
{
    public DateTime EventTime;
    public Product Product; // an enum
    protected double _delta;
    public string Name;
    public double FooSensitivity;
    public double BarSensitivity;
    public double BazSensitivity;
    public double FlopRatio;
    public double FlapCoefficient;
    ...
    public double Value;     // set by overridden CalculateValue
    public double Velocity;  // set by overridden CalculateVelocity

    public PointBase(IDataRepository d, string name, double delta, Product p)
    {
        Name = name;   // just the name, like "Alpha" or "Beta"
        _delta = delta; // follows name, e.g. for Alpha it's always 0.63
        Product = p;
        FooSensitivity = d.GetFooSensitivity(p);
        ... // other setup
    }

    public abstract double CalculateValue();
    public abstract double CalculateVelocity();
}

public class AlphaStatisticPoint
{
    public SimpleStatisticPoint()
    {
        Value = CalculateValue();
        Velocity = CalculateVelocity();
    }

    override double CalculateValue()
    {
        return (fooSensitivity + barSensitivity + bazSensitivity) * Velocity / 2;
    }

    override double CalculateVelocity()
    {
        return FlopRatio * (_delta / FlapCoefficient);
    }
}

public class BetaStatisticPoint
{
    public SimpleStatisticPoint()
    {
        Value = CalculateValue();
        Velocity = CalculateVelocity();
    }

    override double CalculateVelocity()
    {
        return (FlopRatio * 100) * (_delta);
    }

    override double CalculateValue()
    {
        return fooSensitivity * Velocity;
    }
}

// other points...

public class ZetaStatisticPoint
{
    public double Breakeven;

    public SimpleStatisticPoint()
    {
        Value = CalculateValue();
        Velocity = CalculateVelocity();
        Breakeven = CalculateBreakeven();
    }

    override double CalculateVelocity()
    {
        return (FlopRatio * 100) * (_delta);
    }

    override double CalculateValue()
    {
        return fooSensitivity * Velocity;
    }

    override double CalculateBreakeven()
    {
        return 2 * Math.sqrt(fooSensitivity / barSensitivity);
        // This is not defined for other types of statistics, and is only relevant for Zeta-type statistics.
        // For other statistics, we can't even calculate the breakeven; there's no formula for it.
    }
}

public enum Product
{
    Widget,
    Watchet,
    /* Woffet will be added in future, and needs a Term */
}
</code>```

Stuff like Name and Delta should probably be set in the subclasses, since each subclass has one, and each value is unique to each subclass. For example, Alpha's delta value is always 0.63, Zeta's is always 0.21, etc. I'm trying to get away from inheritance though, and the real problem is that Breakeven exists only for Zeta (this is problem #1).

Furthermore (and this is problem #2), I may need to create and set a Term property, but only for Points that have a Product value of Woffet. It doesn't make sense for other products. This property, Term, would be added to all points, so if we're going with inheritance, I'd put it in the superclass. Although I'm starting to think I should just expand Product into a class, and then give it a Term property. But we run into the same problem for the new Product class then: Term only applies to the Woffet product, just like how Breakeven only applies to the Zeta statistic.

I realize that when one comes upon this behavior, it's usually the case the inheritance is not the answer (or so I've gathered?). So, I'm looking for a better way to model this. I was thinking of getting rid of all the subclasses but Zeta, and just giving the superclass a ValueCalculationStrategy and VelocityCalculationStrategy in the constructor (these would calculate Value and Velocity). But in this case, I'm still referring to Zeta as a StatisticPointBase, and the client doesn't know it's a ZetaStatisticPoint. So I'm still stuck. Maybe the problem is that I'm conceptually mixing statistics and points? I could make a separate ZetaStatistic class, and a ZetaBreakeven class, and then use these to compose a ZetaPoint class, but I don't know if this is the right thing to do.

Hopefully I've explained this adequately. If you have any questions, please ask in the comments and I'll do my best to expound on things.


问:
Design strategy for wrapping exceptions
I'm implementing a type of Repository for a framework/library that has (roughly) the following:

```<code>public interface FooRepository {

    boolean contains(String id);

    Foo fetch(String id);

    void commit(Foo foo):
}
</code>```

We can implement it several different ways, depending on what storage medium we're using; for example

```<code>public class FileFooRepositiory implements FooRepository {

    public boolean contains(String id) {
        return fileExistsInFileSystem(id);
    }

    public Foo fetch(final String id) {
        return parseFooFromFile(id);
    }

    public void commit(final Foo foo) {
        writeFooToFile(foo);
    }
}
</code>```

But we can also have

```<code>public class SQLFooRepositiory implements FooRepository {

    public SQLFooRepository(Connection connection) {
        // ...
    }

    public boolean contains(String id) {
        return fooExistsInDatabase(id);
    }

    public Foo fetch(final String id) {
        return parseFooFromDatabase(id);
    }

    public void commit(final Foo foo) {
        writeFooToDatabase(foo);
    }
}
</code>```

There can also be implementations that store Foo objects in a Map<String, Foo> or ones that use external storage systems (appfabric, redis, etc).

However, there are things that can prevent each of these implementation from doing what they are supposed to do. They would each throw a different type of Exception. For SQLException, most things that could happen would use this one exception. For the file-based, it would be some sort of IOException, more specifically, FileNotFoundException, AccessDeniedException, etc.

My question is this: How can I change the contract of the FooRepository interface to allow these types of Exceptions being thrown, without using the throws Exception clause. My initial thought was to have a RepositoryException that would extend RuntimeException and wrap the actual exceptions

```<code>try {
    // ...
}
catch (SQLException sqle) {
    throw new RepositoryException(sqle);
}
</code>```

but I'm not sure if this is the proper strategy I should be using.

答:
I think your strategy is correct (and I accept opinions may vary as to "best").

The client should not care if the underlying repository is a file or a DB server, they care that the commit failed - they need to know that first and handle it. Following on from that, if they wish (e.g. require user intervention or detailed logging) try deal with the underlying issue. Throwing an exception that represents that failure, the RepositoryException is the right thing to do. If that the one exception is sufficient here then use just that one. If the errors are more complex, then include more exceptions - but be judicious.

I generally advise that the exceptions thrown represent the error condition you wish to relay to the client - a "semantic error" if you will, not just the root cause. Inner exceptions (java getCause) are good for expressing the root cause of the failure that occurred.

Basically, I argue that the exception is "I could not do this, because the repository is not available", the inner exception is "I couldn't find the file because the user hasn't got permission."

Defining exceptions runs a fine line between offering the richness of detail required to describe the error to help client code correct it and not being too verbose that it becomes a burden to catch and handle.

ContentLicense: CC BY-SA 3.0

Title: Design strategy for wrapping exceptions


问:
How can I add properties to subclasses and access them without casting from a superclass?
I'm trying to model a multi-dimensional point class in C#. I have about eight different types of points, and there may be more in the future. Right now, I have a superclass (PointBase) that holds all the common behaviors and data. This data includes only simple properties like doubles, strings, enums, and DateTimes (these are the dimensions). The subclasses (let's say 1Point, 2Point, etc.) all override at least things: the methods that have behavior for calculating two of these dimensions. If this behavior were the only changing thing, I could just use the Strategy + Factory pattern and be done with it (and honestly, I probably will refactor those two simple common behaviors out later).

Unfortunately, I'm stuck because some points add a property or two based on their type, or based on values of other properties in the superclass. For example, for point types 1-7, I don't need an additional Breakeven property, but for type 8, I do (this is problem #1).

In addition (this is problem #2), depending on the Product property (which exists and is set in the superclass, and is an enum), I may need to add a Term enum property that would apply to all subclass points. However, only one of my Product enum values needs a term. The others don't.

This situation is complicated by needing to store lists of these points in a List<PointBase> data structure that hides additional public properties. I'd have to cast each PointBase to a 1Point or 2Point or whatever when I took it out, and this (of course) breaks some design principles (separation, at the very least, I think).

Unfortunately, I'm also trying to display these different points on the same WPF DataGrid (in a scheme where the user can select 1Point or 2Point or whatever, and get the points' public properties displayed in the DataGrid). Although all of this code so far is contained within my model  (in a separate DLL), I'm also unsure of how to represent this polymorphism in my view in a DataGrid. I'm totally fine with allowing the DataGrid to just autogenerate columns based on the points' public properties, but again, passing these points around in a List<PointBase> means that there's no way to get at those additional properties I need to add. I thought of instead adding a virtual Dictionary to the superclass called CustomAttributes to which I would add a string key and string value every time I needed to include some additional properties. But this is very annoying, because flattening a Dictionary for a DataGrid is really hard. I'm worried that this is the only way though...

From what I know (which is limited w.r.t. software engineering), I need something like an abstract factory to capture all this polymorpism. But I'm not exactly sure. To recap, I need:

The ability to add public properties to certain subclasses based on their type. For example, for the 8Point subclass, I need to add a Breakeven property, but this property doesn't make sense for other subclasses.

The ability to add public properties to all subclasses based on values of properties in the superclass. For example, if the Product (set in the superclass) is A, I need an additional property added to all subclasses called Term. This property does not apply or make sense for any other products.

I'm not married to inheritance here (in fact, I'd like to do something more elegant/simpler if possible, such as delegation + interfaces), so I'm open to any solutions. Thank you in advance!

EDIT: To give some more context, here is what my setup looks like right now:

```<code>public abstract class StatisticPointBase
{
    public DateTime EventTime;
    public Product Product; // an enum
    protected double _delta;
    public string Name;
    public double FooSensitivity;
    public double BarSensitivity;
    public double BazSensitivity;
    public double FlopRatio;
    public double FlapCoefficient;
    ...
    public double Value;     // set by overridden CalculateValue
    public double Velocity;  // set by overridden CalculateVelocity

    public PointBase(IDataRepository d, string name, double delta, Product p)
    {
        Name = name;   // just the name, like "Alpha" or "Beta"
        _delta = delta; // follows name, e.g. for Alpha it's always 0.63
        Product = p;
        FooSensitivity = d.GetFooSensitivity(p);
        ... // other setup
    }

    public abstract double CalculateValue();
    public abstract double CalculateVelocity();
}

public class AlphaStatisticPoint
{
    public SimpleStatisticPoint()
    {
        Value = CalculateValue();
        Velocity = CalculateVelocity();
    }

    override double CalculateValue()
    {
        return (fooSensitivity + barSensitivity + bazSensitivity) * Velocity / 2;
    }

    override double CalculateVelocity()
    {
        return FlopRatio * (_delta / FlapCoefficient);
    }
}

public class BetaStatisticPoint
{
    public SimpleStatisticPoint()
    {
        Value = CalculateValue();
        Velocity = CalculateVelocity();
    }

    override double CalculateVelocity()
    {
        return (FlopRatio * 100) * (_delta);
    }

    override double CalculateValue()
    {
        return fooSensitivity * Velocity;
    }
}

// other points...

public class ZetaStatisticPoint
{
    public double Breakeven;

    public SimpleStatisticPoint()
    {
        Value = CalculateValue();
        Velocity = CalculateVelocity();
        Breakeven = CalculateBreakeven();
    }

    override double CalculateVelocity()
    {
        return (FlopRatio * 100) * (_delta);
    }

    override double CalculateValue()
    {
        return fooSensitivity * Velocity;
    }

    override double CalculateBreakeven()
    {
        return 2 * Math.sqrt(fooSensitivity / barSensitivity);
        // This is not defined for other types of statistics, and is only relevant for Zeta-type statistics.
        // For other statistics, we can't even calculate the breakeven; there's no formula for it.
    }
}

public enum Product
{
    Widget,
    Watchet,
    /* Woffet will be added in future, and needs a Term */
}
</code>```

Stuff like Name and Delta should probably be set in the subclasses, since each subclass has one, and each value is unique to each subclass. For example, Alpha's delta value is always 0.63, Zeta's is always 0.21, etc. I'm trying to get away from inheritance though, and the real problem is that Breakeven exists only for Zeta (this is problem #1).

Furthermore (and this is problem #2), I may need to create and set a Term property, but only for Points that have a Product value of Woffet. It doesn't make sense for other products. This property, Term, would be added to all points, so if we're going with inheritance, I'd put it in the superclass. Although I'm starting to think I should just expand Product into a class, and then give it a Term property. But we run into the same problem for the new Product class then: Term only applies to the Woffet product, just like how Breakeven only applies to the Zeta statistic.

I realize that when one comes upon this behavior, it's usually the case the inheritance is not the answer (or so I've gathered?). So, I'm looking for a better way to model this. I was thinking of getting rid of all the subclasses but Zeta, and just giving the superclass a ValueCalculationStrategy and VelocityCalculationStrategy in the constructor (these would calculate Value and Velocity). But in this case, I'm still referring to Zeta as a StatisticPointBase, and the client doesn't know it's a ZetaStatisticPoint. So I'm still stuck. Maybe the problem is that I'm conceptually mixing statistics and points? I could make a separate ZetaStatistic class, and a ZetaBreakeven class, and then use these to compose a ZetaPoint class, but I don't know if this is the right thing to do.

Hopefully I've explained this adequately. If you have any questions, please ask in the comments and I'll do my best to expound on things.

答:
I don't fully understand your requirements, but to me it seems you hit a point where C#'s type system is more going to get in the way than actually help you.

I would simply drop the idea of using classes and inheritance and just create a generic key-value store where key it name or type of the propery and value is an object containing the value of the property. Then I would create a code that ensures the invariants about which type of point contains which properties are correct during run time. You might actually try using C# dynamic type, which is basically same thing, but with nicer syntax.


问:
Is there any situation when there's no alternative to instanceof?
It seems to me that instanceof comes from the land of functional programming and is a watered down version of pattern matching and that the OO altenative to it should be dynamic dispatching.

In OO languages (think Ruby), is there any situation where instanceof is the only solution? I can't think of any myself, especially in Ruby where you can patch any class with any methods you like.

答:
While instanceof should be avoided some Java interfaces require it as part of their contract.

For example: javax.security.auth.callback.CallbackHandler.

It defines:

```<code>void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException
</code>```

Callback is an interface with no methods so the only way to differentiate different types of Callback objects is using instanceof. The documentation for CallbackHandler.handle() encourages using instanceof.

Body:
While instanceof should be avoided some Java interfaces require it as part of their contract.

For example: javax.security.auth.callback.CallbackHandler.

It defines:

void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException

Callback is an interface with no methods so the only way to differentiate different types of Callback objects is using instanceof. The documentation for CallbackHandler.handle() encourages using instanceof.


答:
Your solution is correct: repository should throw a generic RepositoryException-type to signal that something went wrong. You wrap the actual exception in that RepositoryException so your logging can get access to the data it needs and your consumers can trap the generic exception and handle it somewhere down the line. Wrapping the actual exceptions hides the implementation details of the concrete repository from the consumer.

The only reason you would differentiate between the exceptions (eg return specific exceptions from the interface) is when the handling of one exception type should be different from the other. In this case I can't really think of a reason you would handle exceptions from the repository differently, so just use the RepositoryException.

Title: Design strategy for wrapping exceptions

Body:
I'm implementing a type of Repository for a framework/library that has (roughly) the following:

```<code>public interface FooRepository {

    boolean contains(String id);

    Foo fetch(String id);

    void commit(Foo foo):
}
</code>```

We can implement it several different ways, depending on what storage medium we're using; for example

```<code>public class FileFooRepositiory implements FooRepository {

    public boolean contains(String id) {
        return fileExistsInFileSystem(id);
    }

    public Foo fetch(final String id) {
        return parseFooFromFile(id);
    }

    public void commit(final Foo foo) {
        writeFooToFile(foo);
    }
}
</code>```

But we can also have

```<code>public class SQLFooRepositiory implements FooRepository {

    public SQLFooRepository(Connection connection) {
        // ...
    }

    public boolean contains(String id) {
        return fooExistsInDatabase(id);
    }

    public Foo fetch(final String id) {
        return parseFooFromDatabase(id);
    }

    public void commit(final Foo foo) {
        writeFooToDatabase(foo);
    }
}
</code>```

There can also be implementations that store Foo objects in a Map<String, Foo> or ones that use external storage systems (appfabric, redis, etc).

However, there are things that can prevent each of these implementation from doing what they are supposed to do. They would each throw a different type of Exception. For SQLException, most things that could happen would use this one exception. For the file-based, it would be some sort of IOException, more specifically, FileNotFoundException, AccessDeniedException, etc.

My question is this: How can I change the contract of the FooRepository interface to allow these types of Exceptions being thrown, without using the throws Exception clause. My initial thought was to have a RepositoryException that would extend RuntimeException and wrap the actual exceptions

```<code>try {
    // ...
}
catch (SQLException sqle) {
    throw new RepositoryException(sqle);
}
</code>```

but I'm not sure if this is the proper strategy I should be using.


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

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

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

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

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

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

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

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

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

The first insert will not be a problem:

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

Both rectangles are thus put in the same subtree.

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

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

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

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

答:
I am assuming that you are indexing elements that are all of about the same size, otherwise life gets complex, or slow, or both……

A Quadtree node  does not need to have a fixed capacity.  The capacity is used to

Allow each tree node to be fixed size in memory or on disk – not required if the tree node contains a variable sized set of elements and you are using a space allocation system that copes.   (E.g. java/c# objects in memory.)

Decide when to split a node.

You could just redefine the rule, so that a node is split if it contains more than “n” district elements, where district is defined in according to the location of the elements.

Or use a “composite element”, so if there are multiply elements at the same location, you introduce a new element that contains a list of these multiply elements.

Title: Quadtree with duplicates


问:
Finding the closest n points to any arbitrary point in two dimensions (r-tree, quadtree, spatial index)
I have a distribution of two dimensional point objects.  How is it possible to find the nearest N number of points to any given point without iterating over the entire collection of points (and only keeping the smallest 'n')?  I will be doing this for every point so brute force technique (which i'm using right now.  There are 12,000+ points within this set so sometimes premature optimization is the.. mature route to take.

I've looked at R-trees however as far as i'm aware they return all points within a given distance of a point, this could potentially work but i'd need to start at an extremely small distance and make successively larger searches until 'n' are found.  Perhaps i'd even need to create a custom geometric circle object and use this to bound the search instead of the default square, thoughts on this approach?  Is the circle necessary?

Are quadtrees any better for this?  Is it possible to traverse from smallest to largest boxes in search of 5 closest points?  It seems this might have potential too -- although i've only taken a cursory glance at this algorithm compared to r-trees.

What's the best way to tackle this accurately without resorting to brute force?

答:
This is easy.

Walk down the tree (quad tree or R-Tree, etc) until you find the lowest node that contains the “search point”.

Then look at the parent of that node, and check all points that is contained within the parent (including sub notes)

If you have not found enough points, then move on to the parent’s parent etc.

Remember

That the nearest point may be in a sibling node.

For more “marks” order the search so that you can bail out as soon as you know that you have the n closet point.

By keeping a stack of nodes as you search down, you don’t need to store a pointer to the parent in each tree note.

How you split a node into sub nodes does not change this, hence R-Tree and Quod Tree can be searched in the same way.


问:
When is background-image not wrapped in: url();
In CSS you declare a background-image by wrapping it inside a url('') ... is there an example when you don't need do this and if not why does it even exist? Even when you're using base64 you still wrap it in a url and I can't seem to find a reasoning for why this is the case. You don't wrap background colour around additional information so why is this the case for a background image.</p>

答:
You can assign different values, not just "url" but also "none", "inherit" and "initial". URL is the function that is used to identify resource and an image is a resource, hence the URL function is used. Using a function also allows you to specify multiple arguments easily and do escaping, which can be handled by the function.

Background-color actually accepts different values and follows the same pattern: there are values such as "none", actual colors such as "black", RGB-codes such as #00FF00 or the RGB-function (which is similar to url): rgb(255, 0, 255)


问:
What is the most obscure sorting algorithm you know?
I just read about cyclesort via a sortvis.org blog post.
This is probably the most obscure one I have heard of so far, since it uses maths that I am not familiar with (detecting cycles in permutations of integer sets).

What is the most obscure one you know?

答: Another obscure "algorithm" is Intelligent Design Sort - but no algorithm is faster or has less memory consumption :)</p>

ContentLicense: CC BY-SA 2.5


问:
How does unit testing work?
I am trying to make my code more robust and I have been reading about unit testing, but I find it very hard to find an actual useful use.
For instance, the Wikipedia example:

```<code>public class TestAdder {
    public void testSum() {
        Adder adder = new AdderImpl();
        assert(adder.add(1, 1) == 2);
        assert(adder.add(1, 2) == 3);
        assert(adder.add(2, 2) == 4);
        assert(adder.add(0, 0) == 0);
        assert(adder.add(-1, -2) == -3);
        assert(adder.add(-1, 1) == 0);
        assert(adder.add(1234, 988) == 2222);
    }
}
</code>```

I feel that this test is totally useless, because you are required to manually compute the wanted result and test it, I feel like a better unit test here would be

```<code>assert(adder.add(a, b) == (a+b));
</code>```

but then this is just coding the function itself in the test.
Can someone provide me with an example where unit testing is actually useful? FYI I am currently coding mostly "procedural" functions that take ~10 booleans and a few ints and give me an int result based on this, I feel like the only unit testing I could do would be to simply re-code the algorithm in the test. edit:
I should also have precised this is while porting (possibly badly designed) ruby code (that I didn't make)

答:
I might have missed it in amongst all the replies but, to me, the main drive behind Unit Testing is less about proving the correctness of a method today but that it proves the continued correctness of that method when[ever] you change it.

Take a simple function, like returning the number of items in some collection.  Today, when your list is based on one internal data structure that you know well, you might think that this method is so painfully obvious that you don't need a test for it.  Then, in several months or years time, you (or someone else) decide[s] to replace the internal list structure.  You still need to know that getCount() returns the correct value.

That's where your Unit Tests really come into their own.

You can change the internal implementation of your code but to any consumers of that code, the result remains the same.

Title: How does unit testing work?


问:
Is there a better pattern than multiple inheritance here?
I'm working on a server implementation for a large game with many gametypes. There are several kinds of interactable entities: players, monsters, objects, vehicles.

All entities share the same base class (which is Cython):

```<code>cdef class Entity:
    cdef public int id
    cdef public double x,y,z,yaw,pitch,speed

    def __init__(self, int id, double x, double y, double z, double yaw, double pitch):
        self.id = id
        self.x = x
        self.y = y
        self.z = z
        self.yaw = yaw
        self.pitch = pitch
        self.speed = 0.1
</code>```

Then there's a subclass for each of the earlier mentioned entity types, these subclasses implement the different packets involved for each of those types.

All entities support position and rotation, and all entities can in theory support different behaviors (and there can be quite a lot depending on the gametype) but often do not need them. There could be around ~90 different behaviors, so supporting all of that on the base MonsterEntity/whatever class doesn't make sense. A lot of those behaviors depend on stuff like health though, so if I don't implement that in a base class I'd have to implement it in a subclass.. but there are so many behaviors like that that are related I'd end up with either a lot of repeated code in different subclasses or thousands of usually unnecessary lines in a single big class.

I decided some kind of composition would make a lot more sense here, so I've tried using multiple inheritance since Python handles it pretty well:

```<code>class EntityHealth(object):
    def __init__(self, maxhealth=20):
        self.health = maxhealth
        self.maxhealth = maxhealth

    def damage(self, amount):
        # damage the entity
        pass

    def setHealth(self, health):
        # set the entity's health
        pass

class EntityInventory(object):
    def __init__(self):
        self.inventory = Inventory()

    def dropAllItems(self):
        # do stuff
        pass

class SlayableMonster(Monster, EntityHealth, EntityInventory):
    def __init__(self, id, name, x, y, z, yaw, pitch):
        Monster.__init__(self, id, name, x, y, z, yaw, pitch, meta, uuid, skinblob)
        EntityHealth.__init__(self, 20)
        EntityInventory.__init__(self)
</code>```

I've heard people argue multiple inheritance should never be used, but this seems like a very concise design.

Some thoughts...

All "behavior" classes would inherit from object or one behavior only for extending that behavior.

The diamond problem shouldn't ever happen as a result because you would never have two classes that inherit from the same class up the tree both applied to the same entity.

So MRO problems should be impossible because the design is simple, there is no complex inheritance hierarchy.

Is this the best solution here, or is there something equally/more concise with the same advantages? I just want to isolate relevant code together while being able to pick which entities need that kind of behavior.

答:
Multiple inheritance is sometimes the right thing to do.

You probably shouldn't inherit both from Car and OilRig, but inheriting from both Walker and Talker can make a lot of sense, particularly if using delegation would introduce a lot of trivial delegating methods that are a pain to maintain. It is particularly benign if it verges on emulating traits or implementing multiple interfaces with default implementations.

It looks as if that is exactly what you are doing here. Certainly you don't have any of the issues (selection of indirectly inherited virtual methods in the diamond configuration, undefined internal layout of derived objects) that caused so many problems in C++ and influenced the conventional wisdom that you should never do it.


答:
Your approach is correct and if you need that your repository client could differentiate between repository exceptions, maybe for showing different kinds of errors, you could also create a tree of Repository Exceptions (always inheriting RuntimeException) like Spring does.

```<code>public class IntegrityConstraintViolationextends RepositoryException {

}

public class Client1 {
  public void consumeRepository(){
    try {
      getRepository.fetch
    }
    catch (IntegrityConstraintViolatione1){
      // do Something special if there is a problem with integrity violation
    }
    catch (RepositoryException e2){
      // do something in any other case
    }
  }
}
</code>```

In this case, you need that the underlying repository implementation have the ability of inform integrity constraint violations. For example the JDBC driver throws IntegrityConstraintViolation

```<code>try {
    // ...
}
catch (SQLIntegrityConstraintViolationException sqle) {
    throw new IntegrityConstraintViolation(sqle);
}
</code>```

The advantage of this is that you always work with your own exception hierarchy tree.

Title: Design strategy for wrapping exceptions

Body:
Your approach is correct and if you need that your repository client could differentiate between repository exceptions, maybe for showing different kinds of errors, you could also create a tree of Repository Exceptions (always inheriting RuntimeException) like Spring does.

public class IntegrityConstraintViolationextends RepositoryException {

}

public class Client1 {
  public void consumeRepository(){
    try {
      getRepository.fetch
    }
    catch (IntegrityConstraintViolatione1){
      // do Something special if there is a problem with integrity violation
    }
    catch (RepositoryException e2){
      // do something in any other case
    }
  }
}

In this case, you need that the underlying repository implementation have the ability of inform integrity constraint violations. For example the JDBC driver throws IntegrityConstraintViolation

try {
    // ...
}
catch (SQLIntegrityConstraintViolationException sqle) {
    throw new IntegrityConstraintViolation(sqle);
}

The advantage of this is that you always work with your own exception hierarchy tree.


问:
Should I put the parameters in constructor or in method? (Python 3)
I have the following code:

```<code>def __init__(self, vocable_file_path, xsd_file_path, word_list_file_path):
    self.vocable_file_path = vocable_file_path
    self.xsd_file_path = xsd_file_path
    self.word_list_file_path = word_list_file_path

def add_values_to_attribute_of_vocables (self, attribute_name, attribute_value, words_attribute_name):
    ... (does the job of adding stuff) ...
</code>```

Only the add_values_to_attribute_of_vocables method uses the three parameters set in the constructor. I could move them into the signature of the method quite easily. What stops me from doing that is, that the method signature would get quite long and I am not sure if it is a good practice to do it.

I read the following question here on PSE:
How does the concept of a class change when passing data to the constructor instead of method parameters?

It makes me think I should put the parameters into the signature of the method, but I am still not sure, if it's the right thing to do.

This is not a black & white question, if there is something fundamentaly bad about the code or my approach, please say so, thanks.

I can post more code, if wanted, but I think the rest of the code is unrelated and might only clutter this question.

EDIT 1:

I now split my code into multiple classes:
http://pastebin.com/WpyKY4fa

Should I now move all the parameters to the constructor of the XLDAttributeAdder class?

答:
It's a bit of a code smell, and your gut feeling is right about this not being a good solution. But instead of passing the arguments, extract the method and the three parameters into a separate class. This class takes the arguments in the constructor and exposes the one method.

Something tells me that this one method is actually doing something that can be split off into another class and that the class that currently has this method is violating the SRP (Single Responsibility Principle) in having that method. I think you'll find that the extracted method and class perfectly fit a responsibility that should be handled by a single class.


答:
The diamond problem shouldn't ever happen as a result because you would never have two classes that inherit from the same class up the tree both applied to the same entity.

Never say never. I bet you within all those 90 behaviors, you will have a diamond problem. Even worse if you don't notice it.

From the small example, it seems you actually want mixins. This way, the behavior would be a field within the subclass and the subclass would implement an interface of that behavior with implementation simply delegation to the instance within the field. This would be too verbose if the language doesn't have explicit support for this, but can be good replacement for multiple inheritance otherwise.

Title: Is there a better pattern than multiple inheritance here?

Body:
I'm working on a server implementation for a large game with many gametypes. There are several kinds of interactable entities: players, monsters, objects, vehicles.

All entities share the same base class (which is Cython):

```<code>cdef class Entity:
    cdef public int id
    cdef public double x,y,z,yaw,pitch,speed

    def __init__(self, int id, double x, double y, double z, double yaw, double pitch):
        self.id = id
        self.x = x
        self.y = y
        self.z = z
        self.yaw = yaw
        self.pitch = pitch
        self.speed = 0.1
</code>```

Then there's a subclass for each of the earlier mentioned entity types, these subclasses implement the different packets involved for each of those types.

All entities support position and rotation, and all entities can in theory support different behaviors (and there can be quite a lot depending on the gametype) but often do not need them. There could be around ~90 different behaviors, so supporting all of that on the base MonsterEntity/whatever class doesn't make sense. A lot of those behaviors depend on stuff like health though, so if I don't implement that in a base class I'd have to implement it in a subclass.. but there are so many behaviors like that that are related I'd end up with either a lot of repeated code in different subclasses or thousands of usually unnecessary lines in a single big class.

I decided some kind of composition would make a lot more sense here, so I've tried using multiple inheritance since Python handles it pretty well:

```<code>class EntityHealth(object):
    def __init__(self, maxhealth=20):
        self.health = maxhealth
        self.maxhealth = maxhealth

    def damage(self, amount):
        # damage the entity
        pass

    def setHealth(self, health):
        # set the entity's health
        pass

class EntityInventory(object):
    def __init__(self):
        self.inventory = Inventory()

    def dropAllItems(self):
        # do stuff
        pass

class SlayableMonster(Monster, EntityHealth, EntityInventory):
    def __init__(self, id, name, x, y, z, yaw, pitch):
        Monster.__init__(self, id, name, x, y, z, yaw, pitch, meta, uuid, skinblob)
        EntityHealth.__init__(self, 20)
        EntityInventory.__init__(self)
</code>```

I've heard people argue multiple inheritance should never be used, but this seems like a very concise design.

Some thoughts...

All "behavior" classes would inherit from object or one behavior only for extending that behavior.

The diamond problem shouldn't ever happen as a result because you would never have two classes that inherit from the same class up the tree both applied to the same entity.

So MRO problems should be impossible because the design is simple, there is no complex inheritance hierarchy.

Is this the best solution here, or is there something equally/more concise with the same advantages? I just want to isolate relevant code together while being able to pick which entities need that kind of behavior.


问:
How to manage tailored/branded web tools?
We produce a number of analysis tools which we re-brand and customise for other businesses to include in their websites.

The tools are typically product comparison, data/trend analysis and report production (in a very particular sector). At present these tools run as a single instance in house, our clients redirect there traffic to us with a URL param specifying the client for branding and customisation.

Up until now we've been using an MVC approach with XSLT views. If a customer wants customisation we add switches in the MVC and/or imports&override in the XSLT. This was manageable for a while but now we have so many versions and customisations for sooo many clients, getting stable builds out the door is becoming a nightmare

We are looking to move to MS asp.mvc3 with using Razor for our views but before this I am wondering are there any standard practices or patterns for developing and managing the kind of mess we are sliding towards?

Cheers,
T

答:
Depends, what's the real problem with the system you have now?  Why are builds unstable?

Sounds like your team needs to Get Organized.

I would start with documenting everything.  Every current build and every change for every customer and customization.  Before changing anything, consult the documentation. Make sure your changes don't break the system.

It's quite possible moving to an entirely new set up is the best way to achieve organization and stability.

Reminds me of a company in Genoa I spoke with once...


问:
How can I check if answer the user typed in is unique in the form submission?
So, I have a form that has security questions and textfields for the user to type in their answer. I want to prevent the user from typing in the same answer to every security question selected. So I am wondering, if there is a .NET attribute I can use to do validation on client side or server side approach that would prevent duplicate answer submission. Every answer that the user types in has to be unique.

So, How can I check if answer the user typed in is unique in the form submission?

I am using ASP.NET MVC 4

答: I think that using Compare will solve your problem. You can try using an equation where you can make sure that the user input is != to the questions that you already have.</p>


问:
Which style to use for features that are not directly driven by humans when using BDD Gherkin language?
Should they be written same way as human workflows, first person "I have entered..." style language etc.? Is the user effectively a gender-less "AI"?

答:
All software is meant to eventually serve at the behest of some human user, and a user story caters to that.  Consequently, any reference in a user story to a machine or other technological item is generally going to be an implementation detail.

Look at this commerce example:

```<code>Story: Returns go to stock

In order to keep track of stock
As a store owner
I want to add items back to stock when they're returned

Scenario 1: Refunded items should be returned to stock
Given a customer previously bought a black sweater from me
And I currently have three black sweaters left in stock
When he returns the sweater for a refund
Then I should have four black sweaters in stock

Scenario 2: Replaced items should be returned to stock
Given that a customer buys a blue garment
And I have two blue garments in stock
And three black garments in stock.
When he returns the garment for a replacement in black,
Then I should have three blue garments in stock
And two black garments in stock
</code>```

Notice that, although the user story is quite detailed, and some "inventory machine" might be involved in the inventory process, that machine is not mentioned in the user story.

Now look at this user story:

```<code>As a Creator, I want to upload a video so that any users can view it.
</code>```

No technology is mentioned.  However, if you begin breaking down the user story into more detail:

```<code>As a Creator, I want to upload a video from my local machine so that any users can view it.

- The “Upload” button will be a persistent item on every page of the site.
- Videos must not be larger than 100MB, or more than 10 minutes long.
- File formats can include .flv, .mov, .mp4, .avi, and .mpg.
- Upload progress will be shown in real time.
</code>```

Now you have the beginning of requirements.

Naturally, nothing prevents you from treating a machine as an actor.  If you wish to do that, simply give the machine a general name describing its role, just as you would a person:

```<code>As a host machine, I want to collect statistical data to track [some resource] usage.
</code>```

Further Reading

Using Gherkin to write user stories that will make sense

How to write meaningful User Stories

Body:
All software is meant to eventually serve at the behest of some human user, and a user story caters to that.  Consequently, any reference in a user story to a machine or other technological item is generally going to be an implementation detail.

Look at this commerce example:

Story: Returns go to stock

In order to keep track of stock
As a store owner
I want to add items back to stock when they're returned

Scenario 1: Refunded items should be returned to stock
Given a customer previously bought a black sweater from me
And I currently have three black sweaters left in stock
When he returns the sweater for a refund
Then I should have four black sweaters in stock

Scenario 2: Replaced items should be returned to stock
Given that a customer buys a blue garment
And I have two blue garments in stock
And three black garments in stock.
When he returns the garment for a replacement in black,
Then I should have three blue garments in stock
And two black garments in stock

Notice that, although the user story is quite detailed, and some "inventory machine" might be involved in the inventory process, that machine is not mentioned in the user story.

Now look at this user story:

As a Creator, I want to upload a video so that any users can view it.

No technology is mentioned.  However, if you begin breaking down the user story into more detail:

As a Creator, I want to upload a video from my local machine so that any users can view it.

- The “Upload” button will be a persistent item on every page of the site.
- Videos must not be larger than 100MB, or more than 10 minutes long.
- File formats can include .flv, .mov, .mp4, .avi, and .mpg.
- Upload progress will be shown in real time.

Now you have the beginning of requirements.

Naturally, nothing prevents you from treating a machine as an actor.  If you wish to do that, simply give the machine a general name describing its role, just as you would a person:

As a host machine, I want to collect statistical data to track [some resource] usage.

Further Reading

Using Gherkin to write user stories that will make sense

How to write meaningful User Stories


问:
Transform Either types in Scala
I have an Either type e.g. Either[A, B] but I want an Either[X, Y] by using two functions A => X and B => Y.
I can do that with fold:

```<code>val myEither: Either[A, B] = ...
myEither.fold(
  a => Left(createNewX()),
  b => Right(createNewY())
)
</code>```

But that seems redundant to me as I have to repeat the Left and Right. I rather want something like:

```<code>val myEither: Either[A, B] = ...
myEither.transformToEither(
  a => createNewX(),
  b => createNewY()
)
</code>```

which transforms an Either[A, B] to an Either[X, Y] by creating a Left for the result of the first function and a Right for the second one. What is the most scala-ish way to do it?

答:
Your first way is probably the best for a one-time deal.  If you need to do this a lot, I would add an implicit map method to Either that gives you the API you want:

```<code>object EitherUtils {
  implicit class ImprovedEither[A, B](e: Either[A, B]) {
    def map[X, Y](fa: A => X, fb: B => Y): Either[X, Y] = {
      e.fold(a => Left(fa(a)), b => Right(fb(b)))
    }
  }
}
</code>```

Scalaz adds a bunch of functionality to either, which might be useful if you care enough about scalaz to decipher their documentation.

However, in general you want to think of Either as a temporary container, occasionally useful for intermediate steps, rather than as something you want to keep around a long time.  If you find yourself wanting to operate extensively on an Either, that should prompt a second look to see if you can refactor it out earlier.

Title: Transform Either types in Scala

Body:
Your first way is probably the best for a one-time deal.  If you need to do this a lot, I would add an implicit map method to Either that gives you the API you want:

object EitherUtils {
  implicit class ImprovedEither[A, B](e: Either[A, B]) {
    def map[X, Y](fa: A => X, fb: B => Y): Either[X, Y] = {
      e.fold(a => Left(fa(a)), b => Right(fb(b)))
    }
  }
}

Scalaz adds a bunch of functionality to either, which might be useful if you care enough about scalaz to decipher their documentation.

However, in general you want to think of Either as a temporary container, occasionally useful for intermediate steps, rather than as something you want to keep around a long time.  If you find yourself wanting to operate extensively on an Either, that should prompt a second look to see if you can refactor it out earlier.


问:
Serial communications: how to verify that received message is a response to the last request sent?
Imagine the following situation. Two devices (master and slave) communicate with each other using any serial protocol like Modbus or HDLC or custom-made one.

Master device sends a request to the slave device. Slave receives the request, but it is too busy to answer right now, so the master sends a second request after a short while. But at this point slave finds some time for processing the previous request and sends a response to it. As a result, master thinks that it received a response to the second request though actually it received a response to the first request. In some situations, this can lead to undesirable consequences.

Is there any standard solution to this problem? Like adding something similar to "salt" to each request?

答:
The most widely-known solution to this problem is the sliding window protocol as used by TCP.  Basically, you transmit a sequence number, and the receiver sends back that sequence number in its response.  The sliding window part is specifying a range of sequence numbers that are currently valid, based on what both sides can prove the other side has definitely sent or received.  The details are too involved to cover in this answer, but they have thought through all the boundary conditions.

The only time you would need more than a simple incrementing sequence number is to avoid a replay attack or similar malicious behavior.


问:
Optional text qualifier in CSV file as input to SSIS package
I receive several CSV files each quarter to process through an SSIS package, and the formatting is inconsistent. This quarter, I encountered what I term optional text qualifiers--text qualifer of double quote (") used at times, but not always. We appear not to have any sway over the people who provide this data to convince them to provide clean, consistent data.

Example of the scenario.

```<code>Bob,7823984234,"Lions, Tigers, Bears",This
Fred,67961654,"Little,Mermaid, ",That
George,4568,"Things,Stuff",The Other Thing
Barney,324578,"Items,",Something Else
Al,2q36789472,"And More",Another
</code>```

Update: Here is what I want to convert the data to.

```<code>"Bob","7823984234","Lions, Tigers, Bears","This"
"Fred","67961654","Little,Mermaid, ","That"
"George","4568","Things,Stuff","The Other Thing"
"Barney","324578","Items,","Something Else"
"Al","2q36789472","And More","Another"
</code>```

I used these steps in a text editor to cleanse the data manually. I suspect a Python script would be the fastest way to do this in a script, and create a good opportunity for me to dive into Python.

Step 1

Search for ÿ - A character not found in the data file

Step 2

Regex Replace this: ("[^"\r\n]*),([^"\r\n]*")

With this: $1ÿ$2

Repeat until no more hits

Step 3

Regex Replace this: "([^"\r\n]*)"

With this: $1

Step 4

Replace this: ("[^"])

With this: "$1

Step 5

Replace this: ,

With this: ","

Step 6

Regex Replace this: ^

With this: "

Step 7

Regex Replace this: $

With this: "

Step 8

Replace this: ÿ

With this: ,

Options

Should I try to resolve this in SSIS in a Script Task?

Cleanse the data in a script outside of the SSIS package?

Look at a Third Party SSIS toolset like Pragmatic Works or Cozyroc?

Some other better approach?

答:
I am not sure what is your end goal in term of cleaning.

Anyway, Python can really help you here.
You can use the csv module in the standard library, or an external package like PETL.

Both will automatically quote field values that need to be quoted.
So for example, if the 3rd column value is Items,, it will be quoted (as it contains the separator character), but if it it Items, it won't be quoted.

You will also be able to pass values to your own methods to clean 1,2, into 1,2 if that is your goal


问:
How do I convince my team that a requirements specification is unnecessary if we adopt user-stories?
We are planning to adopt user-stories to capture stakeholder 'intent' in a lightweight fashion rather than a heavy SRS (software requirements specifications). However, it seems that though they understand the value of stories, there is still a desire to 'convert' the stories into an SRS-like language with all the attributes, priorities, input, outputs, source, destination etc.

User-stories 'eliminate' the need for a formal SRS like artifact to begin with so what's the point in having an SRS? How should I convince my team (who are all very qualified CS folks by the way - both by education and practice) that the SRS would be 'eliminated' if we adopted user-stories for capturing the functional requirements of the system? (NFRs etc can be captured too, but that's not the intent of the question).

So here's my 'work-flow' argument: Capture initial requirements as user-stories and later elaborate them to use-cases (which are required to be documented at a low level i.e. describing interactions with the UI prototypes/mockups and are a deliverable post deployment). Thus going from user-stories to use-cases rather than user-stories to SRS to use-cases.

How are you all currently capturing user-stories at your workplace (if at all) and how do you suggest I 'make a case' for absence of SRS in presence of user-stories?

答: Convincing mgmt to get away from the SRS and to start using user stories is essentially the same thing as convincing mgmt to adopt Agile. There are compelling statistics out there on the productivity benefits of Agile. One example is the presentation VersionOne gave at a 2013 conference. Show mgmt this industry data and if they are the listening type, you have a chance.</p>


问:
Design strategy for wrapping exceptions
I'm implementing a type of Repository for a framework/library that has (roughly) the following:

```<code>public interface FooRepository {

    boolean contains(String id);

    Foo fetch(String id);

    void commit(Foo foo):
}
</code>```

We can implement it several different ways, depending on what storage medium we're using; for example

```<code>public class FileFooRepositiory implements FooRepository {

    public boolean contains(String id) {
        return fileExistsInFileSystem(id);
    }

    public Foo fetch(final String id) {
        return parseFooFromFile(id);
    }

    public void commit(final Foo foo) {
        writeFooToFile(foo);
    }
}
</code>```

But we can also have

```<code>public class SQLFooRepositiory implements FooRepository {

    public SQLFooRepository(Connection connection) {
        // ...
    }

    public boolean contains(String id) {
        return fooExistsInDatabase(id);
    }

    public Foo fetch(final String id) {
        return parseFooFromDatabase(id);
    }

    public void commit(final Foo foo) {
        writeFooToDatabase(foo);
    }
}
</code>```

There can also be implementations that store Foo objects in a Map<String, Foo> or ones that use external storage systems (appfabric, redis, etc).

However, there are things that can prevent each of these implementation from doing what they are supposed to do. They would each throw a different type of Exception. For SQLException, most things that could happen would use this one exception. For the file-based, it would be some sort of IOException, more specifically, FileNotFoundException, AccessDeniedException, etc.

My question is this: How can I change the contract of the FooRepository interface to allow these types of Exceptions being thrown, without using the throws Exception clause. My initial thought was to have a RepositoryException that would extend RuntimeException and wrap the actual exceptions

```<code>try {
    // ...
}
catch (SQLException sqle) {
    throw new RepositoryException(sqle);
}
</code>```

but I'm not sure if this is the proper strategy I should be using.

答:
Been there.

What I did was as follows:

In the file repository class that implements FooRepository:

```<code>    try{
       // try to store
    } catch (IOException e) {
        throw new CouldntStoreFooException(e.getLocalizedMessage());
    }

    try{
       // try to retrieve
    } catch (IOException e) {
        throw new CouldntRetrieveFooException(e.getLocalizedMessage());
    }
</code>```

In the database repository class that implements FooRepository:

```<code>    try{
       // try to store
    } catch (SQLException e) {
        throw new CouldntStoreFooException(e.getLocalizedMessage());
    } etc

    try{
       // try to retrieve
    } catch (SQLException e) {
        throw new CouldntRetrieveFooException(e.getLocalizedMessage());
    }
</code>```

That way the interface signature only knows about CouldntRetrieveFooException or CouldntRetrieveFooException but when you get the exception, and see the log, you can see the actual problem because you passed the original problem (e.getLocalizedMessage()) as a message in the constructor.

The exceptions doesn't need to wrap anything, just:

```<code>public class CouldntStoreFooException extends Exception {

    public CouldntStoreFooException(String reason) {
        super("Problem retrieving foo "+reason);
    }

}
</code>```

...

```<code>public class CouldntRetrieveFooException extends Exception {

    public CouldntRetrieveFooException(String reason) {
        super("Problem retrieving foo "+reason);
    }

}
</code>```

Title: Design strategy for wrapping exceptions

Body:
Been there.

What I did was as follows:

In the file repository class that implements FooRepository:

    try{
       // try to store
    } catch (IOException e) {
        throw new CouldntStoreFooException(e.getLocalizedMessage());
    }

    try{
       // try to retrieve
    } catch (IOException e) {
        throw new CouldntRetrieveFooException(e.getLocalizedMessage());
    }

In the database repository class that implements FooRepository:

    try{
       // try to store
    } catch (SQLException e) {
        throw new CouldntStoreFooException(e.getLocalizedMessage());
    } etc

    try{
       // try to retrieve
    } catch (SQLException e) {
        throw new CouldntRetrieveFooException(e.getLocalizedMessage());
    }

That way the interface signature only knows about CouldntRetrieveFooException or CouldntRetrieveFooException but when you get the exception, and see the log, you can see the actual problem because you passed the original problem (e.getLocalizedMessage()) as a message in the constructor.

The exceptions doesn't need to wrap anything, just:

public class CouldntStoreFooException extends Exception {

    public CouldntStoreFooException(String reason) {
        super("Problem retrieving foo "+reason);
    }

}

...

public class CouldntRetrieveFooException extends Exception {

    public CouldntRetrieveFooException(String reason) {
        super("Problem retrieving foo "+reason);
    }

}


问:
Is there any reason to use C++ instead of C, Perl, Python, etc.?
As a Linux (server side) developer, I don't know where and why should I use C++.

When I'm going for performance, the first and last choice is C.

When "performance" isn't the main issue, programming languages like Perl and Python would be good choices.

Almost all open source applications I know in this area have been written in C, Perl, Python, Bash script, AWK or even PHP, but no one uses C++.

I'm not discussing other areas like GUI or web applications, I'm just talking about Linux, CLI and daemons.

Is there any satisfactory reason to use C++?

答:
According to Linus, no :

When I first looked at Git source code two things struck me as odd:
    1. Pure C as opposed to C++. No idea why. Please don't talk about portability,
    it's BS.

YOU are full of bullshit.

C++ is a horrible language. It's made more horrible by the fact that a
  lot  of substandard programmers use it, to the point where it's much
  much  easier to generate total and utter crap with it. Quite frankly,
  even if  the choice of C were to do nothing but keep the C++
  programmers out,  that in itself would be a huge reason to use C.

In other words: the choice of C is the only sane choice. I know Miles
  Bader jokingly said "to piss you off", but it's actually true. I've
  come  to the conclusion that any programmer that would prefer the
  project to be  in C++ over C is likely a programmer that I really
  would prefer to piss  off, so that he doesn't come and screw up any project I'm involved with.

C++ leads to really really bad design choices. You invariably start
  using  the "nice" library features of the language like STL and Boost
  and other  total and utter crap, that may "help" you program, but
  causes:

infinite amounts of pain when they don't work (and anybody who tells me     that STL and especially Boost are stable and portable is
  just so full     of BS that it's not even funny)

inefficient abstracted programming models where two years down the road     you notice that some abstraction wasn't very efficient, but
  now all     your code depends on all the nice object models around it,
  and you     cannot fix it without rewriting your app.

In other words, the only way to do good, efficient, and system-level
  and  portable C++ ends up to limit yourself to all the things that are
  basically available in C. And limiting your project to C means that
  people  don't screw that up, and also means that you get a lot of
  programmers that  do actually understand low-level issues and don't
  screw things up with any  idiotic "object model" crap.

So I'm sorry, but for something like git, where efficiency was a
  primary  objective, the "advantages" of C++ is just a huge mistake.
  The fact that  we also piss off people who cannot see that is just a
  big additional  advantage.

If you want a VCS that is written in C++, go play with Monotone.
  Really.  They use a "real database". They use "nice object-oriented
  libraries".  They use "nice C++ abstractions". And quite frankly, as a
  result of all  these design decisions that sound so appealing to some
  CS people, the end  result is a horrible and unmaintainable mess.

But I'm sure you'd like it more than git.

```<code>      Linus
</code>```

Body:
According to Linus, no :

When I first looked at Git source code two things struck me as odd:
    1. Pure C as opposed to C++. No idea why. Please don't talk about portability,
    it's BS.

YOU are full of bullshit.

C++ is a horrible language. It's made more horrible by the fact that a
  lot  of substandard programmers use it, to the point where it's much
  much  easier to generate total and utter crap with it. Quite frankly,
  even if  the choice of C were to do nothing but keep the C++
  programmers out,  that in itself would be a huge reason to use C.

In other words: the choice of C is the only sane choice. I know Miles
  Bader jokingly said "to piss you off", but it's actually true. I've
  come  to the conclusion that any programmer that would prefer the
  project to be  in C++ over C is likely a programmer that I really
  would prefer to piss  off, so that he doesn't come and screw up any project I'm involved with.

C++ leads to really really bad design choices. You invariably start
  using  the "nice" library features of the language like STL and Boost
  and other  total and utter crap, that may "help" you program, but
  causes:

infinite amounts of pain when they don't work (and anybody who tells me     that STL and especially Boost are stable and portable is
  just so full     of BS that it's not even funny)

inefficient abstracted programming models where two years down the road     you notice that some abstraction wasn't very efficient, but
  now all     your code depends on all the nice object models around it,
  and you     cannot fix it without rewriting your app.

In other words, the only way to do good, efficient, and system-level
  and  portable C++ ends up to limit yourself to all the things that are
  basically available in C. And limiting your project to C means that
  people  don't screw that up, and also means that you get a lot of
  programmers that  do actually understand low-level issues and don't
  screw things up with any  idiotic "object model" crap.

So I'm sorry, but for something like git, where efficiency was a
  primary  objective, the "advantages" of C++ is just a huge mistake.
  The fact that  we also piss off people who cannot see that is just a
  big additional  advantage.

If you want a VCS that is written in C++, go play with Monotone.
  Really.  They use a "real database". They use "nice object-oriented
  libraries".  They use "nice C++ abstractions". And quite frankly, as a
  result of all  these design decisions that sound so appealing to some
  CS people, the end  result is a horrible and unmaintainable mess.

But I'm sure you'd like it more than git.

      Linus


问:
composer is self-described as inspired by npm, so why does it handle sub-dependencies differently?
As I'm sure anyone reading this knows, the default behavior for npm is to install sub-dependencies within their respective sub-dependency directories themselves (in a new node_modules directory). The default behavior for composer, on the other hand, simply puts all dependencies, including sub-dependencies, into a single vendor directory. As best I can currently surmise, this seems like poor design, since it could cause conflicts if two different dependencies were to use two different specific versions of the same sub-dependency.

But, of course, I think one ought to assume that the designers of composer must have had some good reasons for this deviation from the npm design. What might some of these reasons be?

答:
First of all, I don't think Composer is trying too hard to be a PHP version of NPM - there may be similarities, but differences are to be expected. It may not be the best way to understand it to think of the tool as NPM, Maven, Rake or whatever, but translated into PHP.

Secondly, understand that Composer solves 'problem' of autoloading in PHP. Having two different versions of a given library in your vendor/ directory is not a state of affairs that Composer strives for here, and perhaps that is a good thing. Everything in your vendor/ directory is accessible in your user-land code via the same autoloader. Why would you want more that one class with the same fully-qualified classname? What should happen if you refer to that classname in your own code - which one do you want? I'm not sure we should even want PHP to know what to do when confronted with two different pieces of code each trying to interact with subtly different versions of the same dependency.

Composer replaces told like Pear and Pecl in PHP, and was partly inspired by the PSR-0/4 standards for PHP autoloading. It gives you all your dependencies in one place. It makes dependencies part of your project, not part of its documentation. It uses the semantic versioning that is becoming standard in PHP libraries to find versions of your dependencies that play nicely together, and if there aren't any, it tells you as much.

We've never had a tool like this in PHP before, and the change it has helped precipitate is much greater awareness on the parts of library and framework authors on how their tools work or don't work together. Much is being duke in the community to address these challenges.  Composer may not be exactly like NPM, but its handling of PHP package management is ideally suited to the language, and really fills a gap which made deploying a large PHP application a pain in the neck before.


问:
How to customize Chromium browser from source code
Customizing Chromium includes fixing homepage, removing address bar, .etc. Is it possible to modify the source code or using some compiling options to achieve these goals?</p>

答: Yes it is possible but it's a huge task. Chromium, over the years, has become a huge program with a multitude of moving parts that some are having trouble keeping track of. It's a very large undertaking that assumes you have lots of time and talent to put into it.</p>


问:
Good Coding practice with respect to interface versus class versus super class
I am currently reading the following tutorial and have gotten up through here http://docs.oracle.com/javase/tutorial/java/concepts/interface.html

Maybe I should not be thinking about this question now because the tutorial hasn't brought it up, but I have a question of good practice.  According to the tutorial up to this point, if I want to define an object and its methods, I can do so within either a class, or I can take parts of it that I expect it to share in common with other objects and put it in a super class.  Or, from what I understand, I can do the former but delay defining my method until MAIN by using the interface keyword instead.  I have two questions.

If I have a superclass->class structure, is it possible also to use a sort of "superinterface" instead to delay parts of the definition of methods until the MAIN method? (Please correct my terminology if you know what I mean, and know that I am not speaking correctly.)

Whatever is possible, when is it desirable to use each one from the perspective of efficiency and also of someone who would read my code?

I am a beginner.  Thanks!

Edit: "Example" Code included (as written in the Netbeans IDE) for completion.

```<code>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication3;

/**
 *
 * @author Jeff
 */
class percolation{
    int site1 = 1;
    int site2 = 0;
    int site3 = 1;

    void changesite1(int newValue){
        site1 = newValue;
    }

    void changesite2(int newValue){
        site2 = newValue;

    }

    void changesite3(int newValue){
        site3 = newValue;
    }

    void printStates(){
        System.out.println("site1:" + site1 + " site2:" + site2 + " site3:" + site3);
    }
}

class extendedpercolation extends percolation{
    int site4 = 0;

    void changesite4(int newValue){
        site4 = newValue;
    }
        void printStates1(){
            System.out.println("site1:" + site1 + " site2:" + site2 + " site3:" + site3 + " site4:" + site4);
        }
}

class percolationdemo{
    public static void main(String[] args) {

        extendedpercolation perc1 = new extendedpercolation();
        extendedpercolation perc2 = new extendedpercolation();
        // Invoke methods on
        // those objects
        perc1.changesite1(0);
        perc1.changesite2(0);
        perc1.changesite3(0);
        perc1.changesite4(0);
        perc1.printStates1();

        perc2.changesite1(1);
        perc2.changesite2(0);
        perc2.changesite3(1);
        perc2.changesite4(1);
        perc2.printStates1();
    }
}
</code>```

答:
You pretty much nailed it with your comment

Maybe I should not be thinking about this question now because the tutorial hasn't brought it up

It looks like you're on or near lesson 5, What is an Interface.  I think your answer may be found on or near lesson 67, Interfaces.  (I'm looking at the Table of Contents & just counting each line)

Quoting from that answer,

There are a number of situations in software engineering when it is important for disparate groups of programmers to agree to a "contract" that spells out how their software interacts. Each group should be able to write their code without any knowledge of how the other group's code is written. Generally speaking, interfaces are such contracts.

For example, imagine a futuristic society where computer-controlled robotic cars transport passengers through city streets without a human operator. Automobile manufacturers write software (Java, of course) that operates the automobile—stop, start, accelerate, turn left, and so forth. Another industrial group, electronic guidance instrument manufacturers, make computer systems that receive GPS (Global Positioning System) position data and wireless transmission of traffic conditions and use that information to drive the car.

The auto manufacturers must publish an industry-standard interface that spells out in detail what methods can be invoked to make the car move (any car, from any manufacturer). The guidance manufacturers can then write software that invokes the methods described in the interface to command the car. Neither industrial group needs to know how the other group's software is implemented. In fact, each group considers its software highly proprietary and reserves the right to modify it at any time, as long as it continues to adhere to the published interface.

As you can see, interfaces are used to promise that certain classes will always have certain properties and/or methods.

To make the tutorial example more concrete, just understand that all classes (e.g., Tesla, BMW, Mercedes, Toyota etc.) that implement the IAutonomousControls interface are guaranteed to have all the properties and methods (stop(), start(), turnLeft(), honk()) that are defined in that interface.

Exactly how those properties and methods are implemented are not defined and may be different from class to class.


问:
JIRA: Issue classification, clarification needed
In JIRA, when creating a new issue, i am presented with a number of choices, some of which look like they don't belong.

For example:

"New Feature". This should be a part of a story right? How can one chose when to use "New Feature" and when to use a "Story"?

"New Feature" looks like a type to me or a "Story" to me.

Or, take for instance "Improvement". We can start a whole project with it's own "Epic" for the sole purpose to improve a bunch of things. Should such work be filed under an "Epic" or under something else?

Please clarify

答:
A Jira Kanban Project (out of the box) displays a field called "Epic Link" in each Story, Feature, Task, Defect or several other issue types.
This is true of the both server and cloud versions.

This lends itself to using Epic to mean a collection of stories. Stories and Features can also have sub-tasks assigned. Storys usually give some business value while Tasks do not. It is not clear how a Feature differs from a Story as they have similar behaviour.

Storys hav no field called "Feature Link", but your admin could configure one if you wished to group stories to Features.
Nor are there sub-tasks.

The Structure Plugin (on the server edition) may allow more levels.


问:
"Correct" way to use inheritance
Within a small project, a class Storage is meant to store any type of Item. Now, an Item has a String name, and an interaction. For example, a clock item might implement the interaction increment(int num), whereas a seat might implement sit(bool true).

Should I be simply writing classes for Item, Clock and Seat and letting Seat and Clock inherit from Item? Obviously the interaction they use varies, so short of writing every possible Item's interaction as a virtual method in Item I'm not sure how to deal with all the specific interaction types.

At the moment, I'm finding the Item and then using using conditionals to use the correct behavior on interaction, but that seems sort of roundabout and not so great.

Is there a better way to do this?

答:
Another approach would be to use composition instead of inheritance. We can look to the command pattern for inspiration. We would like to have a common interface while allowing variable actions. Rather than write the behavior into the Item itself (as durron597 does), we could instead create an intermediary object to hold the interactive behavior we want. Let's start with the interface:

```<code>interface Interaction {
    void interact(/** things to pass in **/);
}
</code>```

Now let's create an implementation:

```<code>class ClockInteraction implements Interaction {
    private Clock clock;

    public ClockInteraction(Clock clock) {
        this.clock = clock;
    }

    public void interact() {
        clock.increment(1);
    }
}
</code>```

And another:

```<code>class SeatInteraction implements Interaction {
    private Seat seat;
    private boolean shouldSit;

    public SeatInteraction(Seat seat, boolean shouldSit) {
        this.seat = seat;
        this.shouldSit = shouldSit;
    }

    public void interact() {
        seat.sit(shouldSit);
    }
}
</code>```

The behavior of the Interaction is now separate from the behavior of the Item. Does this provide us with any benefits beyond implementing the behavior directly into the Items? First, we can create multiple behaviors for the same object type:

```<code>class ClockReverseInteraction implements Interaction {
    private Clock clock;

    public ClockReverseInteraction(Clock clock) {
        this.clock = clock;
    }

    public void interact() {
        clock.increment(-1);
    }
}
</code>```

Now I have two different behaviors that can be used on the same object, and I can choose between them at runtime.

We can also compose together multiple Items into a single behavior:

```<code>class SitWhenInteraction implements Interaction {
    private Clock clock;
    private Seat seat;

    public SitWhenInteraction(Clock clock, Seat seat) {
        this.clock = clock;
        this.seat = seat;
    }

    public void interact() {
        seat.sit(clock.value() < 10);
    }
}
</code>```

Now, rather than Storage hold Items, it should hold Interactions instead:

```<code>foreach(Interaction interaction : storage) {
    interaction.interact();
}
</code>```

Title: "Correct" way to use inheritance

Body:
Another approach would be to use composition instead of inheritance. We can look to the command pattern for inspiration. We would like to have a common interface while allowing variable actions. Rather than write the behavior into the Item itself (as durron597 does), we could instead create an intermediary object to hold the interactive behavior we want. Let's start with the interface:

interface Interaction {
    void interact(/** things to pass in **/);
}

Now let's create an implementation:

class ClockInteraction implements Interaction {
    private Clock clock;

    public ClockInteraction(Clock clock) {
        this.clock = clock;
    }

    public void interact() {
        clock.increment(1);
    }
}

And another:

class SeatInteraction implements Interaction {
    private Seat seat;
    private boolean shouldSit;

    public SeatInteraction(Seat seat, boolean shouldSit) {
        this.seat = seat;
        this.shouldSit = shouldSit;
    }

    public void interact() {
        seat.sit(shouldSit);
    }
}

The behavior of the Interaction is now separate from the behavior of the Item. Does this provide us with any benefits beyond implementing the behavior directly into the Items? First, we can create multiple behaviors for the same object type:

class ClockReverseInteraction implements Interaction {
    private Clock clock;

    public ClockReverseInteraction(Clock clock) {
        this.clock = clock;
    }

    public void interact() {
        clock.increment(-1);
    }
}

Now I have two different behaviors that can be used on the same object, and I can choose between them at runtime.

We can also compose together multiple Items into a single behavior:

class SitWhenInteraction implements Interaction {
    private Clock clock;
    private Seat seat;

    public SitWhenInteraction(Clock clock, Seat seat) {
        this.clock = clock;
        this.seat = seat;
    }

    public void interact() {
        seat.sit(clock.value() < 10);
    }
}

Now, rather than Storage hold Items, it should hold Interactions instead:

foreach(Interaction interaction : storage) {
    interaction.interact();
}


问:
How to promote code review as an employee?
I have just graduated not long ago and started to work in a startup company for almost a year. I have introduced git to my current company and they are now happy to use it for version control. I feel that my boss and the company is open to new stuff.

Recently I have heard about the idea of code review and want to give it a try in our company. However, unlike git, I have never done code review. Also, it adds extra work load and I am not sure if everybody is open to accept comment / complain during code review. Is there any suggestion on promoting code review?

答:
Do not call it "code review" when talking to your boss - that can make the impression of a very formal technique which needs special knowledge, training and tools. Call it simply "proof reading" or "four eye principle", and suggest to apply this to all code (especially to your own code) before it goes into production. Its not unlikely when you ask another team member to review your code, others will follow your example and ask you (or some other guy) for reviewing theirs.

After you get your team accustomed to "constant proof reading", the need for better tools or a more systematic process will probably arise from itself, then it is the time to think about tools, not beforehand.


答:
It's great that you're taking initiative to introduce new things to a startup - but if your founders have been through the enterprise experience sometime in their lives, then they'd be wary of any 'processes' that have a tendency to introduce bureaucracy in the company. A simple code review tool can gradually evolve into a mandatory pre-commit review process that is enforced by git hooks!

You need to be shrewd enough to not imply any such thing and steer away from any discussions that head in that way - because, well, everybody hates bureaucracy!

Here's the technique that I had once used:

How do people look at each other's code right now?

In my case, people used to email each other patches (so we kind of did have an informal review process already) - and then you could see people either walking over to each other's desk or writing poetic descriptions to locate the part of code they want to comment on

In class SomeWeirdClassName, function fooButNotJustFoo() should return a SomeStructInADifferentHeader instead of an int!

You can now point at such instances and say, "Hey, this is broken! We can do it in a better way!" and then go on to talk about how a code review tool allows you to add inline comments directly on a particular line of the patch.

Start with a small group, maybe your own team (you can coerce, ahem, convince them over lunch) and ask them to evangelise it with you - talk about how awesome things are in code review land during an all-hands meeting.

If you have an admin guy, then get him drunk on a Friday night and silently add a couple of e-mail aliases to the CC list of all reviews. On Monday, quite a few people would get the code review mails, with contextual comments, live links to the patch and what-not; by the time someone realizes what's going on and removes those aliases from the CC list. But your word is out! Now everyone is talking about "those weird mails that ended up in their inbox by mistake" - the perfect time put on your evangelist hat!

If you prefer to talk directly to your boss, then make sure you highlight the fringe benefits of using the code review tool -

a) The emails ensure that everyone knows what every other developer is working on

b) If some developer decides to call in sick on release day, then you don't have to hack into this computer to get what he was working on - you can just download the patch from the code review tool and check it in yourself

c) Frequently putting others' code into everyone's faces embodies a sense of the prevalent coding culture and prompts everyone to get on the same boat, as opposed to religiously following their own coding style

Lastly, since you've already introduced git (successfully) and people are happy to use it, you already have some street cred riding on you - bank on it to push this new amazing thing that's going to change everyone's life (for the better)!

Title: How to promote code review as an employee?

Body:
I have just graduated not long ago and started to work in a startup company for almost a year. I have introduced git to my current company and they are now happy to use it for version control. I feel that my boss and the company is open to new stuff.

Recently I have heard about the idea of code review and want to give it a try in our company. However, unlike git, I have never done code review. Also, it adds extra work load and I am not sure if everybody is open to accept comment / complain during code review. Is there any suggestion on promoting code review?


答:
If people don't want their work looked at by others because they fear (the repercussions of) criticism, you've a far more serious problem than a lack of code review.

Your actual problem is a toxic environment in which people are severely punished for imperfection, and have got into the habit of hiding mistakes, seeking scapegoats, glossing over problems. Most likely it's also an environment in which success isn't valued, let alone rewarded, because nothing less than perfection is concidered to be the barely acceptable minimum standard.

Unless and until that culture is broken open and people feel free to discuss problems, talk openly about where things go wrong and what should and can be done to fix them, code review is never going to be accepted and forcing it on people will only lead to them spending a lot of time trying to blame their own mistakes on each other because they know full well that the moment something is blamed on them it has instant impact on their career.


问:
Difference between '\n' and '\r\n'
Yes yes, I am aware that '\n' writes a newline in UNIX while for Windows there is the two character sequence: '\r\n'. All this is very nice in theory, but my question is why? Why the carriage return character is extra in Windows? If UNIX can do it in \n why does it take Windows two characters to do this?

I am reading David Beazley's Python book and he says:

For example, on Windows, writing the
  character '\n' actually outputs the
  two- character sequence '\r\n' (and
  when reading the file back, '\r\n' is
  translated back into a single '\n'
  character).

Why the extra effort?

I will be honest. I have known the difference for a long time but have never bothered to ask WHY. I hope that is answered today.

Thanks for your time.

答:
History of the Newline Character (Wikipedia):

ASCII was developed simultaneously by the ISO and the ASA, the predecessor organization to ANSI. During the period of 1963–1968, the ISO draft standards supported the use of either CR+LF or LF alone as a newline, while the ASA drafts supported only CR+LF.

The sequence CR+LF was in common use on many early computer systems that had adopted teletype machines, typically an ASR33, as a console device, because this sequence was required to position those printers at the start of a new line. On these systems, text was often routinely composed to be compatible with these printers, since the concept of device drivers hiding such hardware details from the application was not yet well developed; applications had to talk directly to the teletype machine and follow its conventions.

The separation of the two functions concealed the fact that the print head could not return from the far right to the beginning of the next line in one-character time. That is why the sequence was always sent with the CR first. In fact, it was often necessary to send extra characters (extraneous CRs or NULs, which are ignored) to give the print head time to move to the left margin.

Even after teletypes were replaced by computer terminals with higher baud rates, many operating systems still supported automatic sending of these fill characters, for compatibility with cheaper terminals that required multiple character times to scroll the display.

MS-DOS (1981) adopted CP/M's CR+LF; CP/M's use of CR+LF made sense for using computer terminals via serial lines. This convention was inherited by Microsoft's later Windows operating system.

The Multics operating system began development in 1964 and used LF alone as its newline. Unix followed the Multics practice, and later systems followed Unix.

Title: Difference between '\n' and '\r\n'