问:
How should I approach this from a problem-solving point of view?
I'm currently working on a project to replace some excel worksheets. There is a lot of industry specifics that change quite often and nobody really knows how things should be but every sure enough thinks they know how they shouldn't be.

Project Priorities:

Maintainability - The business processes change frequently. There are like 3-5 different excel templates floating around.

Agile - My boss wants visible changes every week (sometimes less).

Structure - This application will work with several other systems for the entire business process.

Approach & Design:

The DB Schema we took was one where we defined some business logic in the database.
EntityTypes, Properties of those types, and their values are stored in the database (each having their own table ofcourse).

Now, I originally thought about the typical approach, having an Estimate Table defining its properties, Bid Table, Joist Table, etc. (Each of these are EntityTypes by the way).

My boss wanted the DBSchema we're using now (See picture).

Pros/Cons:

Current Schema:

Pros: (Theoretically) Adapts to the data allowing for later changes to be as simple as adding the data to the database.

Cons: Overly complex. I have difficulty even getting my mind around this schema when trying to create the class that will handle it.

Typical/Traditional Schema:

Pros: Simplistic, Anyone without knowledge of the project will be able to pick it up in the future.

Cons: Many Many Tables. Not what we have now.

Situation:

I am currently retrieving the data using a class I made to represent an entity, then converting them into business model classes (Estimate, Bid, Joist...) to pass to the view. This obviously is extra work for the current schema, but I felt that the other way of having the view/controller parse through the model to determine how to display the data (making us only require a few views/controllers) seemed like bad design/programming (though I'm not entirely sure why). Am I correct thinking this schema/design is bad? If, so why?

My Boss wants this Schema because "it may be complex but once the programming is done no more changes should need done." Now obviously the way I'm doing this, that's not true. If I were to do it the way he wants I feel like I might fail to do so as I kept confusing myself with the complexities.

One of my boss's arguments is that you find yourself with a lot of NULL fields when you do the traditional schema (which I feel like you're doing it wrong if that's the case. Maybe in some instances but they have tables with like 30 columns where 10+ majority of the rows have a NULL value for that column).

Will doing all the programming for supporting the current Schema the way he desires be worth the theoretical simplicity to add things in the future? It's not all that much work to add a small feature to a class, and add the display to the view's template using knockout. Especially considering the project is being done in an Agile environment and doing all the work at once then having something to show for it doesn't sound very Agile to me, which is basically what would need done to code the complex classes and display them in the views, not to mention I'd have to code a bunch of HTML helpers (coupling them a bit with Knockout) in order to do this. So personally it sounds like it's just moving the work not saving any. Am I correct in this thought process?

Proposed solution:

I suggested the other day to switch to the other schema and use Entity Framework Code-First to make changes easier (as the way I'm doing it now I have the change the Business Models regardless. Code-First would theoretically allow me to not have to do the Database Changes as well).

My boss's main concern is that with a traditional schema the schema changes and then other systems will need updated as well. Whereas, he states that if we have the current schema then the other systems won't need updated if something changes in the database. Which I don't quite understand since how would it know how to deal with the data? Wouldn't it just mean it too would need complex coding/processes to back it up initially?

Questions:

Why is this schema design bad (if it is)? How can I argue this schema design is bad?

If it is not a bad design, How can I better prepare myself for it? I do my best to Abstract classes/functionality and keep things with single responsibilities.

If it is a bad design, How can I convince my boss to switch to my suggestion (assuming my suggestion is the best/only alternative)?

I understand the last two questions are a but subjective, so it's understandable if they are ignored.

答:
The schema as presented is representing an object model in the database - nothing inherently wrong with that, but it hides the semantic structure of the application...

This kind of thing is common in engineering applications, especially those that originated as complex spreadsheets: everything is reduced to a set of variables and categories and values, so you end up with one 'variable value' table for all the data, resulting in extraordinarily complex queries to retrieve logical entity rows

It appears that the application domain is underspecified; all of the information about the entities and properties that would form the domain schema are buried in the data in the object-model schema.

That makes it incredibly hard to understand the true (semantic) structure of the system, and thus anticipate and apply changes.

ADDENDUM:

The semantics of the system (the object modeling the application/business domain) are hidden within the objects stored in the database - it's a meta/knowledge system. Great for flexibility, difficult to understand without additional tools/effort.

For example, to understand the class structure of a particular area you can't just look at the code for the classes because there isn't any, and the structure of the database tables reveals nothing because they're generic. You'd have to query out the classes and properties and relations and trace through the data to understand what's happening in the application.

If the application model is extremely volatile and/or varied, this may still be the best solution.

Suggestion: query the current class/property structure out of the database and generate the equivalent code (or pseudo-code) representation, and see what the application domain really looks like right now. Imagine a more direct representation (e.g. one table per class) and think about how that database structure would have to change - and how often - to accommodate future directions. You're trading representational complexity for flexibility, this may help you be certain that it is (or is not) a good trade.


问:
In Scrum, how to handle contention/workload at end of sprint
My team started using Scrum a few sprints ago. Our project involves building software interfacing with physical devices (think robots and sensors) and our typical Product backlog usually represent adding controls device to the whole system.

We split down the task close to the example here. Each device integration feature is split into code, tests, integration tests, peer review, etc. Obviously, there is a sequence inherent to each Product Backlog Items. Typically, our sprints last 2 weeks and the team has between 4 to 6 members.

We run into 2 problems at the end of sprints:

The first is to keep everyone busy at end of sprint.

The second (related) one is contention on system. We pretty much end up integrating during the last few days of the sprint. We only have one integration system, so people are often blocked from continuing to work on their task because they can't access the system. Since it is the end of the sprint, there is not much work left to do in the sprint backlog. What should these people work on? Pick up items from the top of the product backlog is not well received from the product owner, since the current items are not done. Working on technical debt will help the project as a whole but won't help completing the sprint.

Are there any best practices to either structure sprints to avoid these issues? Tips to negotiate with product owners?

答:
We've addressed this by adopting the Kanban approach.

We have queues in our tracking software (Jira) with minimum and maximums.

We groom 'as needed'.  Might be once a week, might be 3 times, depends on the limits and the work that get done.

This will help you in getting the product owner focused on keeping your queue with plenty to do and can reduce micro-management of individual tickets.  Just remember that as always change will take time.

We still demo every two weeks and we release weekly.

OwnerDisplayName: Vincent Hubert

ContentLicense: CC BY-SA 3.0


问:
Why does C have no competitors in low level stuff?
As far as I know, C is by far the most widely used language for low level stuff such as systems programming and embedded. Sometimes assembly is used, but that's when you really need to be close to the hardware.

My question is why doesn't C have any competitors in low level development? It might be my ignorance, but I'm pretty sure that C is the obvious (or possibly only) choice for low level programming.

This is as opposed to high level development, where there are many competing programming languages to choose from.

How can you explain this?

答:
Interestingly, I've been doing embedded programming for 13 years:  6 in Ada and 7 in C++.

Anyway, there are a number of factors that make C well-suited for this type of programming:

The runtime/standard library required is very small.

Manual memory management is very useful when memory is limited.

Easy to make deterministic/real time because you don't have to worry about when a garbage collector will run or when an exception will get thrown.

Easy to assign a variable to a specific memory address, which is crucial in writing drivers.

A lot of existing code available.


问:
What happens if I close an InputStream that is passed as an argument?
I have read that Java is pass-by-value, and I've been reading about it in  this question at StackOverflow, but I'm still a bit confused, regarding the close() or shutdown() methods in various classes.

What I want to know is, suppose that I do this:

```<code>public Constructor(){

    if(isProceeding){
        InputStream iStream = new InputStream();
        processStuff(iStream);
    }
}

public void processStuff(InputStream stream){
    //do stuff
    stream.close();
}
</code>```

Does the iStream variable actually get closed in processStuff() method or a copy of it gets closed and iStream itself is still left open?

答:
In your example, iStream actually gets closed in processStuff(), not a copy. I would recommend, however, always closing the InputStream in the same method where you created it, otherwise it's difficult to understand whether it is closed or not. The call to close() should be in a finally { ... } clause so that for sure it is called, even if an exception is thrown, like this:</p>

```<code>package org.company;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

public class Test1 {

    private boolean isProceeding;

    public Test1() {
    }

    public void init(String str) throws IOException {
        if(isProceeding){
            InputStream iStream = null;
            try {
                iStream = new ByteArrayInputStream(str.getBytes("UTF-8"));
                processStuff(iStream);

            } finally {
                iStream.close();
            }
        }
    }

    public void processStuff(InputStream stream){
        //do stuff
    }

    public boolean isProceeding() {
        return isProceeding;
    }

    public void setProceeding(boolean isProceeding) {
        this.isProceeding = isProceeding;
    }

}
</code>```

Body:
In your example, iStream actually gets closed in processStuff(), not a copy. I would recommend, however, always closing the InputStream in the same method where you created it, otherwise it's difficult to understand whether it is closed or not. The call to close() should be in a finally { ... } clause so that for sure it is called, even if an exception is thrown, like this:

package org.company;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

public class Test1 {

    private boolean isProceeding;

    public Test1() {
    }

    public void init(String str) throws IOException {
        if(isProceeding){
            InputStream iStream = null;
            try {
                iStream = new ByteArrayInputStream(str.getBytes("UTF-8"));
                processStuff(iStream);

            } finally {
                iStream.close();
            }
        }
    }

    public void processStuff(InputStream stream){
        //do stuff
    }

    public boolean isProceeding() {
        return isProceeding;
    }

    public void setProceeding(boolean isProceeding) {
        this.isProceeding = isProceeding;
    }

}


问:
Object Design & Cohesion - Issue & potential refactoring
Abstract

I have been trying to get my head around the cohesiveness of some functionality in our code base.  I’ve approached this design in different ways, and lately I’m convinced that I took the wrong approach, as in I incorrectly applied the Single Responsibility Principle.

Issue

The problem domain is a Well, otherwise known as a round hole in the ground.  The current code looks something like this...  I have a set of data in a data only object...

Note: This is not the full code, just method names to keep things short...

```<code>public class WellData
{
    public string Name { get; set; }
    public ICollection<SurveyPoint> SurveyPoints { get; set; }
    public ICollection<GeometryItem> GeometryItems { get; set; }
    public ICollection<TemperaturePoint> WellTemperature { get; set; }
    public ICollection<FluidPoint> WellFluids { get; set; }
}
</code>```

I broke functionality that operates on this data into several small classes. As per below…

```<code>public class ReferenceWellSurvey
{
   ICollection<SurveyPointCalculate> _calculatedSurveyPoints;
   double GetTvdAtDepth(double depth) {}
   double GetAzimuthAtDepthRad(double depth) {}
   double GetInclinationAtDepthRad(double depth){}
   double GetTortuosityPeriodAtDepth(double  depth ) {}
   double GetTortuosityAmplitudeAtDepth(double depth ) {}
}

public class ReferenceWellGeometry
{
   ICollection<GeometryItem> _geometryItems;
   double GetFrictionAtDepth(double depth) {}
   double GetHoleIdAtDepth(double depth) {}
}

public class ReferenceWellTemperature
{
   ICollection<TemperaturePoint> _wellTemperatures;
   double GetTemperatureAtDepth(double depth) {}
   double GetSurfaceTemperature(double depth) {}
}
Etc.
</code>```

I’ve realized lately when looking at our code that I have to glue all this back together to make it usable where I need it in the application logic.  Something like….

```<code>public class ReferenceWellData
{
private IReferenceWellGeometry _refWellGeometry;
private IReferenceWellTemperature _refWellGeometry;
          private IReferenceWell _refWellGeometry;
          private IReferenceFluid _refWellFluid;
       //Proxy functions from each class to glue it all back together…
}
</code>```

A few things that led me to the current mess. The well data class contains several collections of information and if everything is in one class most functions will only operate on a small subset of the data.  At the time I felt that would create low cohesion, now a few months later, I feel these things do actually all belong together.  Additionally, there are several classes in my code that need to call just one method of the ReferenceWellSurvey class, GetTvdAtDepth().  Really what I did didn’t solve this issue.

After thinking more about this, and after reading this Wikipedia article http://en.wikipedia.org/wiki/Cohesion_(computer_science), I’m starting to see that I have committed a few programming sins.

•   Anemic domain model

•   Low cohesion

•   Constructor over injection in code where I try to glue things together

•   Giving a class that depends on GetTvdAtDepth access to other methods that it does not need, violated Interface Segregation Principle.

Solution

I’m looking for that Goldilox design that doesn’t give too much responsibility to any one class (No God Objects), while yet maintaining a good degree of cohesion.

My current thoughts on fixing this are as follows.  Move the functionality that operates on the well data into the same class.  This should help get this functionality closer to Communicational/informational cohesion.

```<code>public class WellData : IWellData
{
    public string Name { get; set; }
    public ICollection<SurveyPoint> SurveyPoints { get; set; }
    public ICollection<GeometryItem> GeometryItems { get; set; }
    public ICollection<TemperaturePoint> WellTemperature { get; set; }
    public ICollection<FluidPoint> WellFluids { get; set; }

   // Operates on SurveyPoint collection
   double GetTvdAtDepth(double depth) {}
   double GetAzimuthAtDepthRad(double depth) {}
   double GetInclinationAtDepthRad(double depth){}
   double GetTortuosityPeriodAtDepth(double  depth ) {}
   double GetTortuosityAmplitudeAtDepth(double depth ) {}
   //Operates on WellGeometry collection
   double GetFrictionAtDepth(double depth) {}
   double GetHoleIdAtDepth(double depth) {}
   //Operates on WellTemperature collection
   double GetTemperatureAtDepth(double depth) {}
   double GetSurfaceTemperature(double depth) {}
}
</code>```

Next to address the issue of several classes needing just one function, I could make this one function into a separate interface IGetTvdAtDepth.  In this way, my classes that need that functionality can depend just on this interface, which I can inherit into my WellData interface, and implement it there, but not tie my other classes to all the functionality that is in my WellData class.

Thoughts on this approach vs. the original approach?  One thing that bothers me about doing things way is that in my API I'm using bastard injection to fulfill the required dependencies of this class... Right now I have three required dependencies, a Survey calculator, and a special class that references data at different measured depths. I'd like to move away from this, but that seems to point back toward having services do more of the lifting...

答: Sometimes design patterns and design guidelines can get in the way of simplicity. The problem you describe (the original problem solved by the software, not the design concerns) sounds like it is best solved by a custom language consisting of composable functions. I use the word "language" in the broader sense, not to imply you need a parser, etc. Your objects hold data, and functions provide the operations on that data. This is not an object-oriented analysis, but a functional analysis. If you then wish to be more object-oriented, you can try to assign some functions to some objects that also encapsulate data. Probably the functional design should come first, then the object-oriented design.</p>


答:
Once I see names like property and propertyValue I usually consider it to be reinventing / reimplementing a key-value data store but in sql.

I can see the argument that this generic approach seems easier to maintain.

However I think you can also make the argument that a little hard coding is code as:

Code can be self-documenting

Comments can be avoided (and so they'll never be out of date with the code!)

tests can be self documenting and read well.

Title: How should I approach this from a problem-solving point of view?

Body:
I'm currently working on a project to replace some excel worksheets. There is a lot of industry specifics that change quite often and nobody really knows how things should be but every sure enough thinks they know how they shouldn't be.

Project Priorities:

Maintainability - The business processes change frequently. There are like 3-5 different excel templates floating around.

Agile - My boss wants visible changes every week (sometimes less).

Structure - This application will work with several other systems for the entire business process.

Approach & Design:

The DB Schema we took was one where we defined some business logic in the database.
EntityTypes, Properties of those types, and their values are stored in the database (each having their own table ofcourse).

Now, I originally thought about the typical approach, having an Estimate Table defining its properties, Bid Table, Joist Table, etc. (Each of these are EntityTypes by the way).

My boss wanted the DBSchema we're using now (See picture).

Pros/Cons:

Current Schema:

Pros: (Theoretically) Adapts to the data allowing for later changes to be as simple as adding the data to the database.

Cons: Overly complex. I have difficulty even getting my mind around this schema when trying to create the class that will handle it.

Typical/Traditional Schema:

Pros: Simplistic, Anyone without knowledge of the project will be able to pick it up in the future.

Cons: Many Many Tables. Not what we have now.

Situation:

I am currently retrieving the data using a class I made to represent an entity, then converting them into business model classes (Estimate, Bid, Joist...) to pass to the view. This obviously is extra work for the current schema, but I felt that the other way of having the view/controller parse through the model to determine how to display the data (making us only require a few views/controllers) seemed like bad design/programming (though I'm not entirely sure why). Am I correct thinking this schema/design is bad? If, so why?

My Boss wants this Schema because "it may be complex but once the programming is done no more changes should need done." Now obviously the way I'm doing this, that's not true. If I were to do it the way he wants I feel like I might fail to do so as I kept confusing myself with the complexities.

One of my boss's arguments is that you find yourself with a lot of NULL fields when you do the traditional schema (which I feel like you're doing it wrong if that's the case. Maybe in some instances but they have tables with like 30 columns where 10+ majority of the rows have a NULL value for that column).

Will doing all the programming for supporting the current Schema the way he desires be worth the theoretical simplicity to add things in the future? It's not all that much work to add a small feature to a class, and add the display to the view's template using knockout. Especially considering the project is being done in an Agile environment and doing all the work at once then having something to show for it doesn't sound very Agile to me, which is basically what would need done to code the complex classes and display them in the views, not to mention I'd have to code a bunch of HTML helpers (coupling them a bit with Knockout) in order to do this. So personally it sounds like it's just moving the work not saving any. Am I correct in this thought process?

Proposed solution:

I suggested the other day to switch to the other schema and use Entity Framework Code-First to make changes easier (as the way I'm doing it now I have the change the Business Models regardless. Code-First would theoretically allow me to not have to do the Database Changes as well).

My boss's main concern is that with a traditional schema the schema changes and then other systems will need updated as well. Whereas, he states that if we have the current schema then the other systems won't need updated if something changes in the database. Which I don't quite understand since how would it know how to deal with the data? Wouldn't it just mean it too would need complex coding/processes to back it up initially?

Questions:

Why is this schema design bad (if it is)? How can I argue this schema design is bad?

If it is not a bad design, How can I better prepare myself for it? I do my best to Abstract classes/functionality and keep things with single responsibilities.

If it is a bad design, How can I convince my boss to switch to my suggestion (assuming my suggestion is the best/only alternative)?

I understand the last two questions are a but subjective, so it's understandable if they are ignored.


问:
Print the next smallest from 2^i * 5^j where i,j >= 0
I was asked this question during a technical phone screening recently and didn't do well. The question is included verbatim below.

Generate {2^i * 5^j | i,j >= 0} sorted collection. Continuously print the next
  smallest value.

Example: { 1, 2, 4, 5, 8, 10...}

"Next smallest" makes me think a min-heap is involved, but I didn't really know where to go from there and no assistance was provided by the interviewer.

Does anyone have advice on how to solve such a problem?

答:
Brian was absolutely right -- my other answer was way too complicated. Here's a simpler and faster way to do it.

Imagine Quadrant I of the Euclidean plane, restricted to the integers. Call one axis the i-axis and the other axis the j-axis.

Obviously, points near to the origin will be picked before points far from the origin. Also note that the active area will move away from the i-axis before it moves away from the j-axis.

Once a point has been used, it won't ever be used again. And a point can only be used if the point directly below it or to the left of it has already been used.

Putting these together, you can imagine a "frontier" or "leading edge" that starts around the origin and them spreads up and right, spreading along the i-axis farther than on the j-axis.

In fact, we can figure out something more: there will be at most one point on the frontier/edge for any given i-value. (You have to increment i more than 2 times to equal an increment of j.) So, we can represent the frontier as a list containing one element for each i coordinate, only varying with the j coordinate and the function value.

Each pass, we pick the minimum element on the leading edge, and then move it in the j-direction once. If we happen to be raising the last element, we add on a new last more element with an incremented i-value and a j-value of 0.

using System;
using System.Collections.Generic;
using System.Text;

namespace TwosFives
{
    class LatticePoint : IComparable<LatticePoint>
    {
      public int i;
      public int j;
      public double value;
      public LatticePoint(int ii, int jj, double vvalue)
      {
          i = ii;
          j = jj;
          value = vvalue;
      }
      public int CompareTo(LatticePoint rhs)
      {
          return value.CompareTo(rhs.value);
      }
    }

    class Program
    {
        static void Main(string[] args)
        {
            LatticePoint startPoint = new LatticePoint(0, 0, 1);

            var leadingEdge = new List<LatticePoint> { startPoint } ;

            while (true)
            {
                LatticePoint min = leadingEdge.Min();
                Console.WriteLine(min.value);
                if (min.j + 1 == leadingEdge.Count)
                {
                    leadingEdge.Add(new LatticePoint(0, min.j + 1, min.value * 2));
                }
                min.i++;
                min.value *= 5;
            }
        }
    }
}
```

Space: O(n) in number of elements printed so far.

Speed: O(1) inserts, but those aren't done every time. (Occasionally longer when the List<> has to grow, but still O(1) amortized). The big time sink is the search for the minimum, O(n) in the number of elements printed so far.

Body:
Brian was absolutely right -- my other answer was way too complicated. Here's a simpler and faster way to do it.

Imagine Quadrant I of the Euclidean plane, restricted to the integers. Call one axis the i-axis and the other axis the j-axis.

Obviously, points near to the origin will be picked before points far from the origin. Also note that the active area will move away from the i-axis before it moves away from the j-axis.

Once a point has been used, it won't ever be used again. And a point can only be used if the point directly below it or to the left of it has already been used.

Putting these together, you can imagine a "frontier" or "leading edge" that starts around the origin and them spreads up and right, spreading along the i-axis farther than on the j-axis.

In fact, we can figure out something more: there will be at most one point on the frontier/edge for any given i-value. (You have to increment i more than 2 times to equal an increment of j.) So, we can represent the frontier as a list containing one element for each i coordinate, only varying with the j coordinate and the function value.

Each pass, we pick the minimum element on the leading edge, and then move it in the j-direction once. If we happen to be raising the last element, we add on a new last more element with an incremented i-value and a j-value of 0.

using System;
using System.Collections.Generic;
using System.Text;

namespace TwosFives
{
    class LatticePoint : IComparable<LatticePoint>
    {
      public int i;
      public int j;
      public double value;
      public LatticePoint(int ii, int jj, double vvalue)
      {
          i = ii;
          j = jj;
          value = vvalue;
      }
      public int CompareTo(LatticePoint rhs)
      {
          return value.CompareTo(rhs.value);
      }
    }

    class Program
    {
        static void Main(string[] args)
        {
            LatticePoint startPoint = new LatticePoint(0, 0, 1);

            var leadingEdge = new List<LatticePoint> { startPoint } ;

            while (true)
            {
                LatticePoint min = leadingEdge.Min();
                Console.WriteLine(min.value);
                if (min.j + 1 == leadingEdge.Count)
                {
                    leadingEdge.Add(new LatticePoint(0, min.j + 1, min.value * 2));
                }
                min.i++;
                min.value *= 5;
            }
        }
    }
}

Space: O(n) in number of elements printed so far.

Speed: O(1) inserts, but those aren't done every time. (Occasionally longer when the List<> has to grow, but still O(1) amortized). The big time sink is the search for the minimum, O(n) in the number of elements printed so far.


问:
How to identify and run the most relevant automated tests?
Suppose you have a reasonably large codebase (0.5 - 1 msloc) with a large test-suite (6-7hr single-threaded runtime; with a mix of unit-tests and integration-tests built with different tools).  You have a proposed patch (or diff or pull-request) for the codebase, and you want to automatically run the most relevant tests.  Running all tests would be too expensive. Running smoke-tests would be too shallow.  The goal is to find something in-between.  By automating the selection of relevant tests, you can help new developers participate in TDD -- and provide timely pre-merge feedback (as part of code-review).

What techniques or arrangements would you use to identify "relevant"?  (A basic example: if a patch modifies "src/(.*).php", then run "phpunit test/{$1}Test.php".) What, if any, existing tools come to mind?  Or what new tools are needed?  Or is it impossible for tooling to help?

(For context: In my particular use-case, I work with LAMP-based web-apps, so tools or techniques that work with PHP/JS/bash are most helpful. But similar issues probably arise with any large app/deep stack, so examples from other stacks could provide insight.)

答:
If your unit tests are taking 6-7 hours to run, something is wrong. They should take a few minutes at most. Note that I say should - I know how difficult this can be in reality. Maybe it's time you start mocking out your objects so that you're not dependent on the filesystem or DB or whatever is slowing you down.

You don't want to have to deal with working out which tests are relevant or which ones should be run all the time - you'll end up spending your time doing that instead of actually doing important stuff, like getting things done.


答:
This is a very common design mistake, most people go through this phase :)

Why is this schema design bad (if it is)? How can I argue this schema design is bad?

It's not taking advantage of a relational database:

No type safety, boom.

No foreign keys, boom.

No referential integrity, boom.

Very difficult to query, boom.

One massive table to store everything will make things slower and more difficult.

How can I convince my boss to switch to my suggestion (assuming my suggestion is the best/only alternative)?

The age old question. Be prepared to spend some time on convincing him, but he may never change their mind. Do some googling and look up article like this one  https://www.simple-talk.com/sql/database-administration/ten-common-database-design-mistakes    and maybe you can do some convincing :)


答:
There are certain static analysis tools that can help determine "test impact", which can then run the effected tests.

But I can't help but feel that you're solving the symptom, not the problem. When I worked in QA, there was one overriding mantra that has helped me as a developer: "don't trust the developer". Even if I could determine "relevant", I wouldn't trust myself to be correct. I mean I can determine that my code is done and correct, why do I need this whole testing exercise?

If your tests are too expensive, then make them cheaper. It's been a decade since I've used a single-threaded unit test framework. 500kloc should take (generously) 5-10 minutes to run through unit tests. Run the unit tests, catch most of the issues and provide you enough certainty to check the code in.

Integration tests might take longer depending on your domain. They shouldn't take so long that you can't run them overnight. Having a day lag time between check-in and integration tests catching your bugs is good enough for most environments, though I would still encourage you to make the integration tests quicker - either by isolating them to particular integration points, eliminating ones that just duplicate unit tests, or by distributing them to a test farm.

Quality is expensive. Skimp on quality and you get what you pay for.

Title: How to identify and run the most relevant automated tests?

Body:
Suppose you have a reasonably large codebase (0.5 - 1 msloc) with a large test-suite (6-7hr single-threaded runtime; with a mix of unit-tests and integration-tests built with different tools).  You have a proposed patch (or diff or pull-request) for the codebase, and you want to automatically run the most relevant tests.  Running all tests would be too expensive. Running smoke-tests would be too shallow.  The goal is to find something in-between.  By automating the selection of relevant tests, you can help new developers participate in TDD -- and provide timely pre-merge feedback (as part of code-review).

What techniques or arrangements would you use to identify "relevant"?  (A basic example: if a patch modifies "src/(.*).php", then run "phpunit test/{$1}Test.php".) What, if any, existing tools come to mind?  Or what new tools are needed?  Or is it impossible for tooling to help?

(For context: In my particular use-case, I work with LAMP-based web-apps, so tools or techniques that work with PHP/JS/bash are most helpful. But similar issues probably arise with any large app/deep stack, so examples from other stacks could provide insight.)


问:
Should we avoid using design patterns in constantly changing projects?
A friend of mine is working for a small company on a project every developer would hate: he's pressured to release as quickly as possible, he's the only one who seem to care about technical debt, the customer has no technical background, etc.

He told me a story which made me think about the appropriateness of design patterns in projects like this one. Here's the story.

We had to display products at different places on the website. For example, content managers could view the products, but also the end users or the partners through the API.

Sometimes, information was missing from the products: for example, a bunch of them didn't have any price when the product was just created, but the price wasn't specified yet. Some didn't have a description (the description being a complex object with modification histories, localized content, etc.). Some were lacking shipment information.

Inspired by my recent readings about design patterns, I thought this was an excellent opportunity to use the magical Null Object pattern. So I did it, and everything was smooth and clean. One just had to call product.Price.ToString("c") to display the price, or product.Description.Current to show the description; no conditional stuff required. Until, one day, the stakeholder asked to display it differently in the API, by having a null in JSON. And also differently for content managers by showing "Price unspecified [Change]". And I had to murder my beloved Null Object pattern, because there was no need for it any longer.

In the same way, I had to remove a few abstract factories and a few builders, I ended up replacing my beautiful Facade pattern by direct and ugly calls, because the underlying interfaces changed twice per day for three months, and even the Singleton left me when the requirements told that the concerned object had to be different depending on the context.

More than three weeks of work consisted of adding design patterns, then tearing them apart one month later, and my code finally became spaghetti enough to be impossible to maintain by anyone, including myself. Wouldn't it be better to never use those patterns in the first place?

Indeed, I had to work myself on those types of projects where the requirements are changing constantly, and are dictated by persons who don't really have in mind the cohesion or the coherence of the product. In this context, it doesn't matter how agile you are, you'll come with an elegant solution to a problem, and when you finally implement it, you learn that the requirements changed so drastically, that your elegant solution doesn't fit any longer.

What would be the solution in this case?

Not using any design patterns, stop thinking, and write code directly?

It would be interesting to do an experience where a team is writing code directly, while another one is thinking twice before typing, taking the risk of having to throw away the original design a few days later: who knows, maybe both teams would have the same technical debt. In the absence of such data, I would only assert that it doesn't feel right to type code without prior thinking when working on a 20 man-month project.

Keep the design pattern which doesn't make sense any longer, and try to add more patterns for the newly created situation?

This doesn't seem right neither. Patterns are used to simplify the understanding of the code; put too much patterns, and the code will become a mess.

Start thinking of a new design which encompasses the new requirements, then slowly refactor the old design into the new one?

As a theoretician and the one who favors Agile, I'm totally into it. In practice, when you know that you'll have to get back to the whiteboard every week and redo the large part of the previous design and that the customer just doesn't have enough funds to pay you for that, nor enough time to wait, this probably won't work.

So, any suggestions?

答:
It would appear the mistake was more to remove the pattern objects, than to use them.  In the initial design, the Null Object appears to have provided a solution to a problem.  This may not have been the best solution.

Being the only person working on a project gives you a chance to experience the whole development process.  The big disadvantage is not having someone to be your mentor.  Taking time to learn and apply best or better practices is likely to pay off quickly.  The trick is identifying which practice to learn when.

Chaining references in the form product.Price.toString('c') violate the Law of Demeter.  I've seen all sorts of issues with this practice, many of which relate to nulls.  A method like product.displayPrice('c') could handle null prices internally.  Likewise product.Description.Current could be handled by product.displayDescription(),  product.displayCurrentDescription(). or product.diplay('Current').

Handling the new requirement for managers and content providers needs to be handled by responding to context.  There are a variety of approaches that can be used.  The factory methods could use different product classes depending on the user class they will be displayed to.  Another approach would be for the product class display methods to construct different data for different users.

The good news is you friend realizes that things are getting out of hand.  Hopefully, he has the code in revision control.  This will allow him to back out bad decisions, which he will invariably make.  Part of learning is to try different approaches, some of which will fail.  If he can handle the next few months, he may find approaches that simplify his life and clean up the spaghetti.  He could try working on fixing one thing each week.


问:
I need a JavaScript runtime environment
I'm reading books on JavaScript programming, and I need an environment like Python's IDLE to type JavaScript commands into and then see the results like you would in IDLE.

Is there an environment where you can do such a thing?

答:
Any of the major browsers (IE, FireFox, Chrome, Safari, etc..) will execute and display the results of JavaScript code that you put into it.

You can open the developer console in Chrome and in IE using F12 and in Firefox using Ctrl+Shift+K. Alternatively you can simply put it into a .html file.

Title: I need a JavaScript runtime environment


问:
Does CC0 allow sublicensing of derived works?
I want to release all my future FOSS projects under a "public domain" license such as CC0. This is in order to avoid the requirement for attribution present in most FOSS licenses, mainly when the code is compiled into a binary, but also when somebody decides to copy a small portion of my code into their own open source project.

So suppose somebody copies a method from my code into their own, which they are planning to release under an MIT license. In order to release the code under MIT, they must claim copyright of the code; but can they claim copyright of the whole if a portion of the code was not their creation? Is that what it means to claim copyright of a derived work?

It may seem strange that somebody could take a piece of public domain code, modify it, and apply a new license to the modified version that imposes further restrictions on its usage, such as the attribution requirement of MIT. But since their additional restrictions would apply only to the modified version and not the original version, this seems legitimate.

My main concern is maximizing the ways in which people can utilize my code, without worrying about licensing requirements, and also to avoid a viral effect where any derivative works have to be themselves licensed under CC0.

答:
I regret to say that I think your question as asked is conflicted.

If you genuinely want to maximise the ways in which people can utilise your code then you must (among other things) allow and encourage them to take that code and pretend it's theirs. If you don't want to require any kind of attribution then you must in effect disclaim authorship as well as ownership. Someone who comes across your code must not even need to know that you wrote it. Even if they got it from you they should be in genuine doubt as to whether you actually stole it from someone else.

At some point this becomes a bit silly. There is a tension between the desire for your code to be used (with or without attribution) and the desire to control how it is used. Creative Commons requires attribution and restricts licensing of derived works, which may not be what you want. You may do better with a simple Public Domain notice and just let people do what they want.

Creative Commons have one of those too: http://creativecommons.org/licenses/publicdomain/

As pointed out, public domain is not the panacea. Since it is not a licence (because it renounces the right to even grant a licence) it really has no legal status and some potential users may not trust it. However, it is a pretty strong indication of intent and may suit your purposes. You could always give up coding, of course.


问:
What payoffs have you seen from taking care of technical debt?
This article on technical debt has some good points, including:

Working on the "technical matters" works best when it is driven by stories. The code base is probably in need of work everywhere, but the payoff will be received only where the code is going to be worked on for user-facing reasons. If no stories are going to pass through some crufty area, working on it is largely wasted.

Therefore, I prefer the approach of taking stories as usual (but probably fewer of them), and following the "boy scout rule" of leaving the campground better than you found it. In other words, wherever the stories lead us, let's write more tests, let's refactor more aggressively.

This approach has at least these advantages:

maintains "best sensible" flow of stories;

provides help from all team talent;

provides for whole team to learn how to keep code clean;

focuses improvement exactly where it is needed;

does not waste improvement that "may" be needed;

I've seen code quality have a very big effect on long-term productivity, so I am a believer that technical debt should be taken care of.  I think the post above makes sense, but I'm not so sure about the last two points.  I'm interested in finding out real experiences of benefits from cleaning technical debt, even if it was not related to user stories.

What positive benefits have you seen from cleaning up your code base and ridding yourself of technical debt? What methods did you use to get the work done?

答:
I can give you one example from my experience.

About 10 or 12 years ago I inherited an application from a team of developers that ended up leaving the company (too long to get into here...).  The system was a large home-grown middleware report generation system.  It ran every week night and generated about 2 dozen Excel reports for senior executives of a Fortune 500 company.  When I inherited it, it took about 5-6 hours to run and during any given week would fail at least 2 nights.

I was not a happy camper to be given this mess.

Initially my plan was just to stop the bleeding and fix the main cause of the failures.  After I became more comfortable with the code base, I started looking for places where I could refactor and add stability and performance.  Over the course of 2 years or so, I made many, many changes to the system.  We retired that system a couple of years ago and at that point the whole process took 45 minutes to run and hadn't generated any issues in years.

A lot of work went into paying down the technical debt but it was well, well worth it.  It was nice not getting any phone calls in the middle of the night that the system failed.  It was nice coming into the office in the monring and seeing nothing but good news in the logs.

(Aside...  After a couple of years I ran into one of the main developers of this system.  He asked me how it was doing and I told him how bad the system was.  He actually apologized and told me he knew it would be a handful to support after he left and wished he had done a better job on it).

ContentLicense: CC BY-SA 2.5


答:
The question seems to be wrong at so many points. But the blatant ones are:

For the Null Object Pattern you mentioned, after the requirements changed, you change a bit of the code. That's fine but it doesn't mean you 'murder' the Null Object Pattern (btw, be careful with your wording, this sounds too extreme, some people too paranoiac won't see this as funny at all).

Many people have correctly said, design patterns are very much about labeling and naming a common practice. So think about a shirt, a shirt has a collar, for some reason you remove the collar or part of the collar. The naming and labeling changes, but it is still a shirt in essence. This is exactly the case here, minor changes in detail which doesn't mean you have 'murdered' that pattern. (again mind the extreme wording)

The design you talked about is bad because when the requirement changes come as minor things, you make massive strategic design changes all over the places. Unless the high-level business problem changes, you can't justify making massive design change.

From my experience, when minor requirements come, you only need to change small part of the codebase. Some might be a bit hacky, but nothing too serious to substantially affect maintainability or readability and often a few lines of comment to explain the hacky part will suffice. This is a very common practice as well.

Title: Should we avoid using design patterns in constantly changing projects?

Body:
A friend of mine is working for a small company on a project every developer would hate: he's pressured to release as quickly as possible, he's the only one who seem to care about technical debt, the customer has no technical background, etc.

He told me a story which made me think about the appropriateness of design patterns in projects like this one. Here's the story.

We had to display products at different places on the website. For example, content managers could view the products, but also the end users or the partners through the API.

Sometimes, information was missing from the products: for example, a bunch of them didn't have any price when the product was just created, but the price wasn't specified yet. Some didn't have a description (the description being a complex object with modification histories, localized content, etc.). Some were lacking shipment information.

Inspired by my recent readings about design patterns, I thought this was an excellent opportunity to use the magical Null Object pattern. So I did it, and everything was smooth and clean. One just had to call product.Price.ToString("c") to display the price, or product.Description.Current to show the description; no conditional stuff required. Until, one day, the stakeholder asked to display it differently in the API, by having a null in JSON. And also differently for content managers by showing "Price unspecified [Change]". And I had to murder my beloved Null Object pattern, because there was no need for it any longer.

In the same way, I had to remove a few abstract factories and a few builders, I ended up replacing my beautiful Facade pattern by direct and ugly calls, because the underlying interfaces changed twice per day for three months, and even the Singleton left me when the requirements told that the concerned object had to be different depending on the context.

More than three weeks of work consisted of adding design patterns, then tearing them apart one month later, and my code finally became spaghetti enough to be impossible to maintain by anyone, including myself. Wouldn't it be better to never use those patterns in the first place?

Indeed, I had to work myself on those types of projects where the requirements are changing constantly, and are dictated by persons who don't really have in mind the cohesion or the coherence of the product. In this context, it doesn't matter how agile you are, you'll come with an elegant solution to a problem, and when you finally implement it, you learn that the requirements changed so drastically, that your elegant solution doesn't fit any longer.

What would be the solution in this case?

Not using any design patterns, stop thinking, and write code directly?

It would be interesting to do an experience where a team is writing code directly, while another one is thinking twice before typing, taking the risk of having to throw away the original design a few days later: who knows, maybe both teams would have the same technical debt. In the absence of such data, I would only assert that it doesn't feel right to type code without prior thinking when working on a 20 man-month project.

Keep the design pattern which doesn't make sense any longer, and try to add more patterns for the newly created situation?

This doesn't seem right neither. Patterns are used to simplify the understanding of the code; put too much patterns, and the code will become a mess.

Start thinking of a new design which encompasses the new requirements, then slowly refactor the old design into the new one?

As a theoretician and the one who favors Agile, I'm totally into it. In practice, when you know that you'll have to get back to the whiteboard every week and redo the large part of the previous design and that the customer just doesn't have enough funds to pay you for that, nor enough time to wait, this probably won't work.

So, any suggestions?


答:
I think you committed much worse sin in your work : you didn't write any test. From much more abstract way, you didn't look at your code from the perspective of code which will use it. It is much easier to see abstractions and possible ways to divide the behavior if you actually write the code that uses what you are trying to design. So it leads to actually better design.

Next thing to note is that while SRP is nice, it should not be used without the rest of the OLID principles. SRP reminds us that there is something called responsibility and that we should be aware of it. But it is extremely bad rule to base your design on, simply because responsibility can mean anything from "responsibility to add two numbers" to "responsibility to solve all customer's problems". This makes SRP quite ambiguous. Software design is complex discipline and basing it on just one principle is foolish at best.

Title: Object Design & Cohesion - Issue & potential refactoring

Body:
Abstract

I have been trying to get my head around the cohesiveness of some functionality in our code base.  I’ve approached this design in different ways, and lately I’m convinced that I took the wrong approach, as in I incorrectly applied the Single Responsibility Principle.

Issue

The problem domain is a Well, otherwise known as a round hole in the ground.  The current code looks something like this...  I have a set of data in a data only object...

Note: This is not the full code, just method names to keep things short...

```<code>public class WellData
{
    public string Name { get; set; }
    public ICollection<SurveyPoint> SurveyPoints { get; set; }
    public ICollection<GeometryItem> GeometryItems { get; set; }
    public ICollection<TemperaturePoint> WellTemperature { get; set; }
    public ICollection<FluidPoint> WellFluids { get; set; }
}
</code>```

I broke functionality that operates on this data into several small classes. As per below…

```<code>public class ReferenceWellSurvey
{
   ICollection<SurveyPointCalculate> _calculatedSurveyPoints;
   double GetTvdAtDepth(double depth) {}
   double GetAzimuthAtDepthRad(double depth) {}
   double GetInclinationAtDepthRad(double depth){}
   double GetTortuosityPeriodAtDepth(double  depth ) {}
   double GetTortuosityAmplitudeAtDepth(double depth ) {}
}

public class ReferenceWellGeometry
{
   ICollection<GeometryItem> _geometryItems;
   double GetFrictionAtDepth(double depth) {}
   double GetHoleIdAtDepth(double depth) {}
}

public class ReferenceWellTemperature
{
   ICollection<TemperaturePoint> _wellTemperatures;
   double GetTemperatureAtDepth(double depth) {}
   double GetSurfaceTemperature(double depth) {}
}
Etc.
</code>```

I’ve realized lately when looking at our code that I have to glue all this back together to make it usable where I need it in the application logic.  Something like….

```<code>public class ReferenceWellData
{
private IReferenceWellGeometry _refWellGeometry;
private IReferenceWellTemperature _refWellGeometry;
          private IReferenceWell _refWellGeometry;
          private IReferenceFluid _refWellFluid;
       //Proxy functions from each class to glue it all back together…
}
</code>```

A few things that led me to the current mess. The well data class contains several collections of information and if everything is in one class most functions will only operate on a small subset of the data.  At the time I felt that would create low cohesion, now a few months later, I feel these things do actually all belong together.  Additionally, there are several classes in my code that need to call just one method of the ReferenceWellSurvey class, GetTvdAtDepth().  Really what I did didn’t solve this issue.

After thinking more about this, and after reading this Wikipedia article http://en.wikipedia.org/wiki/Cohesion_(computer_science), I’m starting to see that I have committed a few programming sins.

•   Anemic domain model

•   Low cohesion

•   Constructor over injection in code where I try to glue things together

•   Giving a class that depends on GetTvdAtDepth access to other methods that it does not need, violated Interface Segregation Principle.

Solution

I’m looking for that Goldilox design that doesn’t give too much responsibility to any one class (No God Objects), while yet maintaining a good degree of cohesion.

My current thoughts on fixing this are as follows.  Move the functionality that operates on the well data into the same class.  This should help get this functionality closer to Communicational/informational cohesion.

```<code>public class WellData : IWellData
{
    public string Name { get; set; }
    public ICollection<SurveyPoint> SurveyPoints { get; set; }
    public ICollection<GeometryItem> GeometryItems { get; set; }
    public ICollection<TemperaturePoint> WellTemperature { get; set; }
    public ICollection<FluidPoint> WellFluids { get; set; }

   // Operates on SurveyPoint collection
   double GetTvdAtDepth(double depth) {}
   double GetAzimuthAtDepthRad(double depth) {}
   double GetInclinationAtDepthRad(double depth){}
   double GetTortuosityPeriodAtDepth(double  depth ) {}
   double GetTortuosityAmplitudeAtDepth(double depth ) {}
   //Operates on WellGeometry collection
   double GetFrictionAtDepth(double depth) {}
   double GetHoleIdAtDepth(double depth) {}
   //Operates on WellTemperature collection
   double GetTemperatureAtDepth(double depth) {}
   double GetSurfaceTemperature(double depth) {}
}
</code>```

Next to address the issue of several classes needing just one function, I could make this one function into a separate interface IGetTvdAtDepth.  In this way, my classes that need that functionality can depend just on this interface, which I can inherit into my WellData interface, and implement it there, but not tie my other classes to all the functionality that is in my WellData class.

Thoughts on this approach vs. the original approach?  One thing that bothers me about doing things way is that in my API I'm using bastard injection to fulfill the required dependencies of this class... Right now I have three required dependencies, a Survey calculator, and a special class that references data at different measured depths. I'd like to move away from this, but that seems to point back toward having services do more of the lifting...


答:
Do the functional classes have any real internal state or possible variations / alternative implementations?  If not, could you rewrite ReferenceWellGeometry to be a utility class with all static methods that take one additional parameter for the collection? e.g.

```<code>static double GetFrictionAtDepth( ICollection<GeometryItem> _geometryItems, double depth) {}
</code>```

This style has drawbacks, but for your case it might simplify all the class dependency / injection issues.

Body:
Do the functional classes have any real internal state or possible variations / alternative implementations?  If not, could you rewrite ReferenceWellGeometry to be a utility class with all static methods that take one additional parameter for the collection? e.g.

static double GetFrictionAtDepth( ICollection<GeometryItem> _geometryItems, double depth) {}

This style has drawbacks, but for your case it might simplify all the class dependency / injection issues.


答: I find http://jsfiddle.net/ to be a good test environment for trying things out (in JavaScript, HTML and CSS), if you just want to try something easily and now using your browser.</p>

Title: I need a JavaScript runtime environment

Body:
I'm reading books on JavaScript programming, and I need an environment like Python's IDLE to type JavaScript commands into and then see the results like you would in IDLE.

Is there an environment where you can do such a thing?


答:
Mainstream browsers’ dev tools have a console for executing expressions:

Evaluating Expressions in Google Chrome.

The Internet Explorer F12 tools console.

The Firefox Console.

See also Plunker. It is similar to the already mentioned jsFiddle.

Title: I need a JavaScript runtime environment


问:
Paranoid Encryption
Call me paranoid, but I really like to keep my stuff secret, but readily available on the cloud. So, asking this question.

How safe and reliable is encryption software (e.g., truecrypt)? The reason I ask is that, what is I encrypt my data today with this software and after a couple of years, the software is gone ! What happens to my encrypted data?

Is it equally safe to AES encrypt using 7-zip? Will it provide the same level or equivalent level of encryption as truecrypt or other encryption software? (I agree truecrypt will be better because of the container encryption it gives.) And what happens if 7-zip shuts down after 5 years?

I am sorry if I am sounding paranoid, but I am coming back to my original question... Is there any application/software independent encryption? Meaning, can I encrypt with one software and decrypt with another so that I will not be dependent on just one vendor? I want my encryption to depend ONLY on the password and NOT on the encryption program/software?

The next question, can I write my own program that does AES/stronger encryption when I give it a passphrase, so that I don't need to depend on third party software for encryption? If yes, which language supports the same?

Can someone give me a heads up as to where to look for in case of writing my own encryption program?

答:
AES is the way to go, it is the current standard encryption algorithm, which means it is the ones which gets more attention and real-life cracking attempts, a great value for assessing encryption algorithm's security.

You can go for AES256 to benefit of the longer key, 256 bit of asymmetric encryption keys are over-killing for today's (realistic) understanding of future proofing.

If you want more, you can resort in multiple encryption chaining, i.e. AES+Twofish+Serpent, that is sound for current consensus.

However, future proofing would be quite tricky: casting guess about possible math breakthroughs is plainly not possible, and even doing projections about computing power growth in one or few decades introduces huge levels of uncertainty.

This, as of theoretical backgorund, but on end user's perspective implementation is often the critical point, and that is the main point why no one without solid experience in cryptography (both math and real life implementations) should not consider about implementing their own cryptosystem.

A software providing encryption should sustain a large amount of test and auditing (better if public, security by obscurity, as a role of thumb, does not work), starting from the code (does it contains malicious code? i.e. how can we trust Truecrypt after recent concerns about latest releases?) and even the compiler (was it tampered to inject malicious code?), the software and the platform itself (does it leaks memory or temp files? does the OS keylog me? is there some malware running? etc), and finally the hardware - was it tampered? is it safe from TEMPEST-like attacks intercepting em signals from keyboard, screen, internal circuitry - that's why some high grade encryption solution runs on dedicated hardware.

Title: Paranoid Encryption


问:
How can a true Vector be implemented in Haskell?
How could a true Vector type be implemented in Haskell? In order for something to be a Vector, it has to be stored sequentially in memory, with O(1) random access. But Haskell hides its memory management, and its datatypes describe trees! So how could you express that kind of requirement?

答:
Not all data types in Haskell are trees. There are also the builtin types like functions or Int. Among those you find the type Array which gives you O(1) access to its elements.

Some compilers, like GHC, also provide unboxed arrays. Those use less memory and per element access is faster, but that does not change the complexity of course.

On top of those arrays one can build data types similar to std::vector in C++. An example is the vector library.


问:
Why is first column of list called 0th in so many languages?
If you want first element of list or array you reference it as 0 in many languages (like C or Clojure). Is there are some really good reasons why the programming languages was design this way?

In old days in assembly languages it makes perfect sense because all possible values needs to be used.

But what are nowadays to keep it this way? There is very little advantage when modulo arithmetic and ranges (Wikipedia article.) but not much more.

On a disadvantages side it should be: It makes confusion because it human language the first is connected with 1 (1st and it is not in english only). It makes confusion even in XPath (W3School:"Note: In IE 5,6,7,8,9 first node is[0], but according to W3C, it is [1]."). There are troubles between languages who use 1-based and 0-based system.

Want to know hat are the good reasons to use zero-based numbering and why even creator of new languages (like Clojure) choose this way?

答:
Yes, there is a reason:

If you have a 1-based address, the starting (first) element of array anyway lies at zero address. It is a contradiction, that disappears if you have a 0-based address. And for the last you have one operation less when counting the address of the element. So, C in array addresses counting is more effective than much older 1-based FORTRAN-4.

Of course, in ours days the reasons must be based on human convenience. And counting row = natural numbers sequence starts at 1. And anyone of us started to count from 1 in childhood.

But people who makes new languages are thinking on two more reasons - grammatic simplicity of the language and customs of probable future users. And if you want to get C users, you'll introduce 0-based address.

And, of course, one more, purely subjective reason - language authors can simply like or dislike one of these schemes.


问:
Why is the use of constructors discouraged when creating prototypes?
Quick background: In JavaScript, the constructor function for each object type has a prototype property. The prototype refers to an object that each constructed object uses as the next step up in its prototype chain. When you want one type to inherent from another type, you can set the prototype of the child type to a new instance of the parent type.

For example:

```<code>var Parent = function() { /* constructor business */ }
Parent.prototype.parentProp = "some parent property";

var Child = function() { /* constructor business */ }
Child.prototype = /*** !! Some prototype object goes here !! ***/
</code>```

My question asks about what code should go in the "Some prototype object goes here" spot in the above code. My first instinct is to construct an instance of the parent (i.e., new Parent()), but in a comment to an answer on Is this a safe way of copying one objects prototype to another?, one user writes:

No, do not use new bar() for the prototype object!

(...which is an opinion I've seen in many SO answers and comments, but this is the only example I have on hand at the moment.)

The other option is to use Object.create(Parent.prototype) as Child.prototype. As far as I know, this also creates a new Parent instance, but it does not run the Parent constructor.

Can someone explain why running the constructor function should be avoided when generating a prototype object from a parent type? Is there some significant technical problem that arises (perhaps with multiple levels of inheritance)? Or is such a pattern a misuse of constructors that clashes with some prototypical best practice (e.g., running the constructor when creating a prototype violates some separation of concerns)?

答:
Now that my understanding has broadened a bit, I'd like to build on Esailija's answer with a specific example:

One specific concern is that a constructor can set instance-specific properties. Thus, if you use a prototype object created with new, all your child instances could share a single constructor-defined instance-specific property from the prototype.

For example, suppose Parent instances each have a unique id property set as construction time:

```<code>var Parent = function() { this.id = Math.random(); }
Parent.prototype.parentProp = "some parent property";

var Child = function() { /* constructor business */ }
Child.prototype = new Parent();
</code>```

This will cause all Child instances to share a single prototype id property inherited from the one and only new Parent() object used as Child.prototype.

A better approach for this case is to use Object.create and directly call the parent constructor (if needed) inside the child constructor:

```<code>var Parent = function() { this.id = Math.random(); }
Parent.prototype.parentProp = "some parent property";

var Child = function() {
    // run `this` through the Parent constructor function
    Parent.apply(this, arguments);
}
Child.prototype = Object.create(Parent.prototype);
</code>```

Body:
Now that my understanding has broadened a bit, I'd like to build on Esailija's answer with a specific example:

One specific concern is that a constructor can set instance-specific properties. Thus, if you use a prototype object created with new, all your child instances could share a single constructor-defined instance-specific property from the prototype.

For example, suppose Parent instances each have a unique id property set as construction time:

var Parent = function() { this.id = Math.random(); }
Parent.prototype.parentProp = "some parent property";

var Child = function() { /* constructor business */ }
Child.prototype = new Parent();

This will cause all Child instances to share a single prototype id property inherited from the one and only new Parent() object used as Child.prototype.

A better approach for this case is to use Object.create and directly call the parent constructor (if needed) inside the child constructor:

var Parent = function() { this.id = Math.random(); }
Parent.prototype.parentProp = "some parent property";

var Child = function() {
    // run `this` through the Parent constructor function
    Parent.apply(this, arguments);
}
Child.prototype = Object.create(Parent.prototype);


问:
What's the easiest way to comply with open source licenses?
I'm really confused by all the open source licensing details like "I wrote a web application, which should run on a computer not owned by me. My software uses the library/language xxx. Is this considered a software redistribution of xxx?".

Looking at the first four pieces of used software reveals four different licenses (MIT, BSD, Apache, Apache/Eclipse dual). It looks like all of them require about the same, i.e., list them and link to their license.

So I thought I could simplify my life by simply voluntarily listing all the software used. The list is not that long and it'd call it fair. But there are obstacles like copyrighted names, trademarks and such stuff. I've tried to google for an example, but found nothing but the EPSON list (which is for a piece of hardware).

Does anyone know an example of software list for a web application? I'm especially curious what's the best solution for Java (run on a computer not owned by me).

答:
Software distribution happens when you make a copy of software and give that copy to someone else for their use. If the software remains under your ownership and control and you give it to someone acting as your agent to carry out your instructions that is not distribution.

You don't have to list everything and you never could. Just acknowledge a few of the biggies.

There are two important factors you did not mention.

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

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

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

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


问:
Building software with version numbers
This is not a question about how to number versions.

We have an application with a certain version numbering scheme. We also have a Jenkins CI server (soon to be replaced with Atlassian's Bamboo) that regularly builds our software. The application displays the version number, so it's written in one of the files in our code base.

We don't want to manually change the version number before releasing a version. Our current solution is that we have a Jenkins job that changes the version number in our code base, commits it, tags the repository with the version number, pushes it and then packages the application for distribution. The problem with that is that we have to decide to release a version before the build succeeds or fails.

What we want to do is this: have Jenkins regularly build our product and run the unit tests. Afterwards, we want to select a passing build and release it with a certain version number.

In summary, this is the process I want:

Jenkins builds and tests our product regularly.

When we want to release a version, we can select the last passing build from Jenkins and check to release it.

The resulting release should include the version number.

The commit that was built and released should be tagged with the release number.

What is the best practice for releasing product versions? Is there a process that will meet my demands?

答:
We have a similar situation, and I setup our build/release process like this:

Our version numbers consist of four parts (major, minor, build, revision). The first two parts are only changed after a release, the other two change for every build. In our case, the major & minor version come from Jenkins build parameters, the revision number comes from subversion and the build version is the build number of the Jenkins job that performs the build. You could also read the major & minor version number from a file in the repository.

Jenkins writes a file that the software uses to determine its version number.

This file is archived within Jenkins as a build artifact, but it is not committed to the repository.
This way, each build has a unique version number that can be retrieved later, but the version numbers are not tracked in the repository.

For making a release, we have a Release Jenkins job. This job doesn't actually build anything, but it takes as parameter which build we want to release and tags the repository at the revision for that build and marks the build in Jenkins as a release (using the build promotions feature). The file with version information can be used to determine the version number that should be encoded in the tag name.

Title: Building software with version numbers


答:
In the same way today you might think about browser portability/compatibility (will this code run in Opera!?) people back in the day worried about CPU/architecture portability (will this code run on VAX!?).

So every CPU vendor ended up shipping their systems with a C compiler. It was relatively simple to implement, a lot of people knew C, it performed well, and you didn't have to force your platform's developers to dig into the underlying assembly.

Unlike Javascript though, this momentum wasn't "baked in" to the architecture. C ended up gaining momentum because of its relationship with Unix and the efforts that were undergone to make Unix and C portable across CPUs. You can read a lot about this on C's wikipedia page. In short: Unix was one of the first OS's written not in assembly, but in a higher level language, C. Furthermore C developed explicitly out of attempts to port Unix to other architectures. So those lessons learned helped make C a portable systems langauge. Bell labs created the Portable C Compiler or pcc that made it much easier to support many CPU architectures.

Due to explicit efforts to port Unix everywhere -- C got ported everywhere. So the language was one of the first to have low-level portability baked into its bones and popularity and momentum grew from there.

Title: Why does C have no competitors in low level stuff?

Body:
As far as I know, C is by far the most widely used language for low level stuff such as systems programming and embedded. Sometimes assembly is used, but that's when you really need to be close to the hardware.

My question is why doesn't C have any competitors in low level development? It might be my ignorance, but I'm pretty sure that C is the obvious (or possibly only) choice for low level programming.

This is as opposed to high level development, where there are many competing programming languages to choose from.

How can you explain this?


答: As for actual IDE's, you could use Visual Studio (express version is free). They've added better JS intellisense support in the past few releases.</p>

Title: I need a JavaScript runtime environment


答:
Jetbrains Webstorm is an IDE you can use as well, if that's the sort of thing you're looking into.

Otherwise, there's probably an eclipse plugin.

There's also Sublime Text and Atom, that, with a few plugins, can do it very well.

Title: I need a JavaScript runtime environment


问:
Is SourceSafe really safe?
Having spent all morning trying to check something in - I now realise I've lost a couple of days worth of work.

Its happened before - and is apparently common occurrence with SourceSafe.  Can SourceSafe be used successfully, without problems, and if so, how?

答: My view on VSS ? I declined a few job offers (very well paid) because they requested "VSS proficiency". And I am sure there is a couple of other people here who did the same.</p>

Title: Is SourceSafe really safe?


答:
Because C is the lowest level portable language that exists and is widely supported.

I remember ages ago in some demo was a comment:

C is just asm with more macros.

And it's true. C is just high level enough to allow writing portable code, but low level enough that you can see what exactly is going on at the level of bytes in memory when you need it and thus can easily connect it to the few assembly bits that absolutely need to be platform specific. And absolutely nothing happens implicitly so when you write nothing, it will take no cycles, which is important when you are writing performance critical things in internals of operating system, threading library and such.

All other programming languages except assembly are higher level. Which is great for writing applications, but for the system code being able to judge what the compiled code with look like is more important.

C is also the least common denominator. You can call C library from any other language. Other languages have various requirements that make mixing them difficult.


问:
How is oData different from a REST service?
I am looking into writing a web service API and I am thinking of creating a REST service. What does OData means in this context? Can you please explain the difference between OData and REST? </p>

答:
REST is an Architectural Style of building Web Services. It's just a model that says that you could use HTTP and its verbs (POST/PUT/GET etc.) to perform CRUD on Resources exposed by your Services. But REST lacks any details on how the URLs should look like, how to request/response formats should look like, how to query information or at a basic level what operations and resources a service supports in the first place!

In the world of XML based web services, we have SOAP, WSDL, WS-* which define the standards that enable interoperability across various services and their clients.

OData is trying to do this for the REST based web services.

It defines $metadata in CSDL format to explain what (entity/complex) types your service supports and their properties, their data types, how are your types related, and if your service also support some special operations beyond the traditional CRUD.

OData standardizes the URL formats for your resources viz., /Entity, /Entity('id') or /Entity(key1=value1, key2=value2)... and so on..

OData standardizes the request/response formats in JSON and AtomXml on how the data and its metadata is structured.

OData also specifies a very rich query language to enable consumers query your services for precise information they are looking for - with the help of $filter, $orderby, $skip, $top, $expand.

OData helps you describe your entire Data Model - Entities and their Relationships and support all kinds of operations like CREATE, UPDATE, DELETE, GET, MERGE and even CUSTOM OPERATIONS on these Entities and/or Relationships.

OData v4 is now an OASIS standard which many improvements on top of its earlier versions. The ecosystem for OData is slowly growing.


答:
Most of the answers centre on JavaScript code in the web browser. If you're interested in server-side JavaScript code (or more generally, JavaScript code in non-browser environments), then you've got a couple of other options:

Node.js is currently the most popular server-side JavaScript framework and comes with an interactive console. Once you've installed Node.js, you can start the console either from the Start Menu, or by typing node into a terminal.

There's also a reasonable amount of buzz about Nashorn, which is bundled with Java 8. Once you've installed JDK 8, you can start the console by running jjs, which depending on your OS will either be available automatically from the terminal, or found at $JAVA_HOME/bin/jjs.

Title: I need a JavaScript runtime environment


问:
Is there any practical use for the empty type in Common Lisp?
The Common Lisp spec states that nil is the name of the empty type, but I've never found any situation in Common Lisp where I felt like the empty type was useful/necessary. Is it there just for completeness sake (and removing it wouldn't cause any harm to anyone)? Or is there really some practical use for the empty type in Common Lisp? If yes, then I would prefer an answer with code example.

For example, in Haskell the empty type can be used when binding foreign data structures, to make sure that no one tries to create values of that type without using the data structure's foreign interface (although in this case, the type is not really empty).

答:
Type declarations and static analysis

Since no value typed as NIL can exist, the use of the NIL type is mostly relevant for static analysis.
T and nil respectively represent the top (⊤) and bottom (⊥) types and might be used when inferring the type of expressions.
Consider the following example:

(defun the-thing () (length (1+ (read))))
```

<ul>
<li>The type of <code>(read)</code> is <code>T</code>, because if reading succeeds, the returned value can be anything.</li>
<li>The type of <code>(1+ (read))</code> is necessarily <code>NUMBER</code>, because the returned value exists only if no error is signaled. And if this is the case, we know from the type analysis of <code>+</code> that the result is a number.</li>
<li>The type of <code>(length (1+ (read)))</code> is <code>NIL</code>, because <code>length</code> returns a value only for <em>sequences</em>. Giving a number is guaranteed to signal an error, and thus the possible values returned by the function is represented by the empty type (an empty set of values).</li>
</ul>

<p>This kind of analysis is not only theoretical, it actually happens with SBCL:</p>

<pre class="lang-lisp prettyprint-override"><code>* (defun the-thing () (length (1+ (read))))
; in: DEFUN THE-THING
;     (LENGTH (1+ (READ)))
;
; caught WARNING:
;   Derived type of (+ (READ) 1) is
;     (VALUES NUMBER &OPTIONAL),
;   conflicting with its asserted type
;     SEQUENCE.
;   See also:
;     The SBCL Manual, Node "Handling of Types"
;
; compilation unit finished
;   caught 1 WARNING condition

THE-THING
</code>```

Moreover, here we can see the derived type of THE-THING:

* (describe #'the-thing)

#<FUNCTION THE-THING>
  [compiled function]

Lambda-list: ()
Derived type: (FUNCTION NIL NIL)
Source form:
  (SB-INT:NAMED-LAMBDA THE-THING
      NIL
    (BLOCK THE-THING (LENGTH (1+ (READ)))))
```

<p>The <code>NIL</code> type means: this functions will not return successfully.
For example, in SBCL, the <code>error</code> function has the following declared type:</p>

<pre class="lang-lisp prettyprint-override"><code>(FUNCTION (T &REST T) NIL)
</code>```

... because it never returns a value but signals a condition.
You can use NIL in function type declarations explicitely if you want.
By the way, please notice that SBCL only gives a warning and still compiles your code: you can call the function and it will trigger the dynamic checks that will lead you to the debugger, etc.

NIL implies the absence of "normal" termination. If the body of your function is (loop), the return type is also NIL. But sometimes you can return normally but you do not have any value to return (like void in C).
That is why (values &optional) is more appropriate as a type declaration when you return no value successfully. This is done by using the (values) expression in your code. The &optional keyword in the type declaration is necessary because the type (values) would allow you to return more values (see comments).

Is nil necessary?

Some implementations might not care about nil. Since you wonder if we could remove it without causing any harm, maybe trying to remove the nil type from an implementation could be an nice experiment, to see how much does effectively break in practice.

Foreign types

Regarding foreign types, I doubt it can be used like in Haskell, while conforming to the spec, because:

the behavior is undefined if a value does not match the declared type, and

there is already a type for foreing values in CL (but maybe I did not understand exactly what you mean with foreign types and Haskell).

This is purely speculative, but maybe a variable (or an array) of type nil
allocated by a CL runtime could be handled to some foreign code (using implementation-specific means). This is not how it is done in CFFI.

The case of nil arrays

I don't know why (maybe just because there is no check) some implementations like SBCL allow arrays of elements of type nil, defined as follows:

(type-of (make-array 10 :element-type nil) )
=> (SIMPLE-ARRAY NIL (10))
```

<p>However, one can't access an element of such an array:</p>

<pre class="lang-lisp prettyprint-override"><code>(aref (make-array 10 :element-type nil) 5)
</code>```

The following type error is caught: "The value 5 is not of type (MOD 4611686018427387901)." Moreover, the backtrace contains the following line, where the actual content of the array is seen containing random values:

(AREF "¿[¦^D^P^@^@^@×[" 5)
```

<p>Accessing uninitialized arrays has undefined consequences (see comments).
Consequences are undefined even if the actual data is only referenced and not effectively used for its content, as in: </p>

<pre class="lang-lisp prettyprint-override"><code>(LENGTH (LIST (AREF (MAKE-ARRAY 1) 0)))
</code>```

The example is taken from the "Issue UNINITIALIZED-ELEMENTS Writeup".

I see no reason to allow the creation of arrays of type NIL in the first place, apart maybe from allocating (useless?) memory. As said above, maybe there is an implementation-specific, totally not portable way for some lisp to use such arrays, and pass them to foreign functions, but I doubt it.

Finally, in Maclisp's manual (note that Maclisp predates Common Lisp), it is said that NIL arrays can be used as arrays of type T but make the garbage collector behave as if no objects were referenced.
However, here is what the manual says about them:

Type NIL arrays are discouraged even for those who think they know what they are doing.

Body:
Type declarations and static analysis

Since no value typed as NIL can exist, the use of the NIL type is mostly relevant for static analysis.
T and nil respectively represent the top (⊤) and bottom (⊥) types and might be used when inferring the type of expressions.
Consider the following example:

(defun the-thing () (length (1+ (read))))

The type of (read) is T, because if reading succeeds, the returned value can be anything.

The type of (1+ (read)) is necessarily NUMBER, because the returned value exists only if no error is signaled. And if this is the case, we know from the type analysis of + that the result is a number.

The type of (length (1+ (read))) is NIL, because length returns a value only for sequences. Giving a number is guaranteed to signal an error, and thus the possible values returned by the function is represented by the empty type (an empty set of values).

This kind of analysis is not only theoretical, it actually happens with SBCL:

* (defun the-thing () (length (1+ (read))))
; in: DEFUN THE-THING
;     (LENGTH (1+ (READ)))
;
; caught WARNING:
;   Derived type of (+ (READ) 1) is
;     (VALUES NUMBER &OPTIONAL),
;   conflicting with its asserted type
;     SEQUENCE.
;   See also:
;     The SBCL Manual, Node "Handling of Types"
;
; compilation unit finished
;   caught 1 WARNING condition

THE-THING

Moreover, here we can see the derived type of THE-THING:

* (describe #'the-thing)

#<FUNCTION THE-THING>
  [compiled function]

Lambda-list: ()
Derived type: (FUNCTION NIL NIL)
Source form:
  (SB-INT:NAMED-LAMBDA THE-THING
      NIL
    (BLOCK THE-THING (LENGTH (1+ (READ)))))

The NIL type means: this functions will not return successfully.
For example, in SBCL, the error function has the following declared type:

(FUNCTION (T &REST T) NIL)

... because it never returns a value but signals a condition.
You can use NIL in function type declarations explicitely if you want.
By the way, please notice that SBCL only gives a warning and still compiles your code: you can call the function and it will trigger the dynamic checks that will lead you to the debugger, etc.

NIL implies the absence of "normal" termination. If the body of your function is (loop), the return type is also NIL. But sometimes you can return normally but you do not have any value to return (like void in C).
That is why (values &optional) is more appropriate as a type declaration when you return no value successfully. This is done by using the (values) expression in your code. The &optional keyword in the type declaration is necessary because the type (values) would allow you to return more values (see comments).

Is nil necessary?

Some implementations might not care about nil. Since you wonder if we could remove it without causing any harm, maybe trying to remove the nil type from an implementation could be an nice experiment, to see how much does effectively break in practice.

Foreign types

Regarding foreign types, I doubt it can be used like in Haskell, while conforming to the spec, because:

the behavior is undefined if a value does not match the declared type, and

there is already a type for foreing values in CL (but maybe I did not understand exactly what you mean with foreign types and Haskell).

This is purely speculative, but maybe a variable (or an array) of type nil
allocated by a CL runtime could be handled to some foreign code (using implementation-specific means). This is not how it is done in CFFI.

The case of nil arrays

I don't know why (maybe just because there is no check) some implementations like SBCL allow arrays of elements of type nil, defined as follows:

(type-of (make-array 10 :element-type nil) )
=> (SIMPLE-ARRAY NIL (10))

However, one can't access an element of such an array:

(aref (make-array 10 :element-type nil) 5)

The following type error is caught: "The value 5 is not of type (MOD 4611686018427387901)." Moreover, the backtrace contains the following line, where the actual content of the array is seen containing random values:

(AREF "¿[¦^D^P^@^@^@×[" 5)

Accessing uninitialized arrays has undefined consequences (see comments).
Consequences are undefined even if the actual data is only referenced and not effectively used for its content, as in:

(LENGTH (LIST (AREF (MAKE-ARRAY 1) 0)))

The example is taken from the "Issue UNINITIALIZED-ELEMENTS Writeup".

I see no reason to allow the creation of arrays of type NIL in the first place, apart maybe from allocating (useless?) memory. As said above, maybe there is an implementation-specific, totally not portable way for some lisp to use such arrays, and pass them to foreign functions, but I doubt it.

Finally, in Maclisp's manual (note that Maclisp predates Common Lisp), it is said that NIL arrays can be used as arrays of type T but make the garbage collector behave as if no objects were referenced.
However, here is what the manual says about them:

Type NIL arrays are discouraged even for those who think they know what they are doing.


问:
Isn't striving for elegance counter-productive?
Many questions have been asked about the nature of elegant code and design, but the underlying assumption seems to be that elegance is a good thing. Therefore it is acceptable or even desirable to make some extra effort to create elegant solutions.

But is it really worth it?

I am not asking what is elegant; neither am I asking about good code. I assume that "you know it when you see it", and it can also be vaguely characterized by verifying that there is nothing left to take away, in a sense that the mental model you have in your mind is expressed directly and unobscrured in the language of your choice (programming language, object oriented design, relational schema etc.), without distractions.

However, a corollary to it is that elegance is always relative (and in a way subjective); it depends on what you think the problem is and what the solution should look like. The problem of course is that both the problem domain and your understanding of it constantly change (additionally, your knowledge about the programming language / patterns / tools develops, but that's not what I am mainly concerned about).

This implies that in order to keep your design elegant, you have to constantly rethink it as the problem / your undestanding of it evolves. Practically, doing so would result in almost endless refactoring.

Furthermore, I even maintain that by striving to develop elegant solutions maintainability necessarily suffers. The most elegant solutions are the most tightly coupled to the problem domain, for if they weren't, then there would be something to take away from it, hence they would not be most elegant anymore. If there is something abundant in your solution, then you can simplify it and make it more elegant by removing that abundant part, right?

But then, sometimes, when you have a really elegant design and are required to implement a change, you first have to "untighten" your solution, just in order to be able to make an unforeseen (as are most of them) change at all. However, the open/closed-principle states that this should not be necessary. So, another more concrete formulation of the question is:

To some degree, aren't elegance and open/closed-principle at odds with each other?

What do you think?

答:
However, the open/closed-principle states that this should not be necessary. This isn't a useful interpretation of the open/closed principle.

There's always a requirement your design can't accommodate. Think of it this way - a program can be thought of as a domain-specific library whose components are combined in a particular way by the main function to solve some problem. If that library is flexible enough to do anything without changes to its source code, it's turing complete and you've created a programming language on top of your programming language and are no better off than when you started. For the library to be useful, it must be tailored to a particular, well-defined task, and when the scope of that task changes, so must the library.

(The alternative would be to write every possible program, so that when someone comes to you with a new problem, you've already got a program for it. The problems with this approach are obvious.)

Furthermore, the Open/Closed Principle was originally coined in 1988, when our understanding of OOP was still young. Bertrand Meyer probably had extension through inheritance in mind when he coined it, but it turns out you can't override arbitrary methods from a class without your subclasses breaking further down the line when the parent class is updated. In other words, the base class must be designed up front with inheritance in mind and you can only safely override whatever the base class says you may override. The promise of being able to handle unforeseen tasks through ad-hoc inheritance was false. This is known as the fragile base class problem.

I'd argue that a more useful interpretation of the open/closed principle is that when the scope of your requirements expand to include a new task, your code shouldn't be hard-coded to that particular instance of the task. E.g. If you now need to sort a list of dates, it's very likely you'll need to sort other kinds of things as well. Rather than writing a function that only sorts lists of dates, you might as well write a function that can sort lists of anything that can be compared.

Once you acknowledge that it's insane to anticipate every possible change, "elegance" is simply finding the most clear, simple, or "beautiful" way of expressing the solution to your particular problem.