问:
Designing interfaces to hardware
I am writing a library in C++ that is used by customers to interface with hardware. There are many different devices that I need to support.

For the sake of simplicity, assume I have 2 Widgets, WidgetA and WidgetB, which are physical devices. Both Widgets communicate using the same protocol and share a lot in common. They both support 20 of the same generic configuration settings. However, WidgetA supports 10 unique configuration settings, and WidgetB supports a different 10 unique configuration settings. WidgetB also has a few unique functions as well.

The user of my library may know up front what Widget they are using (ex. if a user bought just 1 Widget and wanted to use my library to communicate with it, they would probably use it knowing they only have to communicate with WidgetA). However, there are other scenarios where the user would want to write an application that handles a variety of Widgets. The type of Widget would have to be determined at runtime by interrogating the actual device.

So my question is: What should the design be for this library?
I was thinking of the following options:

1) Just brute force it and put all functions in a generic Widget class. The physical Widget would be checked before running a command and an error would occur if trying to use a function not supported by the device. This ends up being a lot of functions in 1 class, with no end in sight as new Widgets need to be supported in the future.

```<code>class Widget
{
    void setAddress(int);       //generic config setting
    void setUniqueOption1(int); //config only supported by physical WidgetA's
    void setUniqueOption2(int); //config only supported by physical WidgetB's
    ...                         //repeat for all config and functions supported by any Widget!
}
</code>```

2) Add a separate class for each Widget (or each Widget that has unique features). This seems like a good idea, but users would have to create a generic Widget first, then determine what type of physical device they are talking to, then create the specific WidgetA class to access that functionality.

```<code>class Widget
{
    void setAddress(int);       //generic config setting
}

class WidgetA : public Widget
{
    void setUniqueOption1(int); //config only supported by physical WidgetA's
}

class WidgetB: public Widget
{
    void setUniqueOption2(int); //config only supported by physical WidgetB's
}
</code>```

3) Create a pure virtual ConfigOption class. Create config classes for each Widget that contain options that the user sets up all at once. The user just uses the generic Widget class which has a function setCustomConfig which takes these custom widget config classes.

```<code>class Widget
{
    void setAddress(int);                      //generic config setting
    void setCustomConfig(const ConfigOption&); //used to set all custom config settings
}

class ConfigOption = 0;

class WidgetA_Config : public ConfigOption
{
    //user sets all the options, then sends the object to the Widget::setCustomConfig
    int optionA1;
    int optionA2;
    int optionA3;
}

class WidgetB_Config : public ConfigOption
{
    int optionB1;
    int optionB2;
}
</code>```

This is my first time trying to write a good interface to interface with hardware, which is throwing a wrench in my normal logic that I use for writing code. Are any of these ideas the right approach? Or is there some design that I am missing?

In reality, there are ~30 of these Widgets, and the potential for more each day. Some are 99% similar to what I would consider the "Base Widget" while others can have these unique features (configuration and functionality).

答:
I think you might be getting stuck trying to make your class hierarchy fit a real-world taxonomy, and that's not always the best approach.

First of all, objects are almost always created by some sort of factory in this situation.  You call a probe function that returns a list of all Widgets connected to your system, already instantiated.  Then you can configure it.

The model I see most often for a hardware device is a data structure of features.  Take a mouse, for example.  They all have at least two buttons and at least two axes, but some have much more.  Rather than have a base Mouse class with derived classes like ThreeButtonWithScroll, they each have an Axes collection and a Buttons collection.  The user of the class isn't allowed to add or remove an axis or button, but he can set properties on each.

Say you had some sort of weird mouse without any buttons.  Its Buttons collection would just be empty, and therefore unconfigurable.  You're not exposing any interfaces that aren't allowed to be used.

If your list of features is so huge that you would be only using a small portion of them on any given device, then you could create an array of Features in your Widget class.  Where a Feature could be the unique things about some mice like Vibration or BacklightColor.  These can also be relatively generic, like BooleanFeature("Vibration", disabled, callback).

Title: Designing interfaces to hardware


问:
Linking stylesheets and scripts when using server side includes
I am working on a site where I want to have a header and footer on each page, so I thought about using server side includes for this. I have not used them before so I am a little bit unsure about best practices when it comes to styling my site. I am currently including the styles and scripts in the file for the header, and when it is included the rest of the site is styled, and it seems to be working, but I was wondering if there are best practices I should be aware of when it comes to this.</p>

答:
Well the most usual way to do that is to declare each stylesheet and js to its own file and make them abstract to use.

But if you declare all styles and js of your website in single files and include them, they can conflict with each other or with code you write later on and destroy the layout.

ContentLicense: CC BY-SA 3.0


问:
How does big O notation indicate upper bound on a function?
Suppose we have a function, f(n)=n+10.
We say that f(n)∈O(n), meaning O(n) represents the upper bound of the function.

It is also true that f(n)∈O(n2) or f(n)∈O(n3) and so on.

So how can we say that O(n) is the upper bound when O(n2) is comparatively bigger bound and O(n3) is much bigger bound?

Please forgive if I have understood the concept wrongly.

答:
It is very easy to eliminate your confusion because it comes from a single word:

O(n) represents the upper bound of the function.

That's incorrect. The correct statement is:

O(n) represents an upper bound of the function.

Big-O notation does not mean that the function named in the notation is the least upper bound, just that it is an upper bound.

When we rewrite your question as:

How can we say that O(n) is an upper bound when O(n2) is comparatively bigger bound and O(n3) is much bigger bound?

the question becomes clear.  There are no humans taller than 100 meters tall; that's an upper bound on human height.  200 meters and 10000000 meters are also upper bounds; the existence of larger upper bounds does not mean that a smaller upper bound is not also an upper bound. None of these are the least upper bound.

Now, in your example O(n) happens to be the least upper bound on the function you give. There are also larger upper bounds, as you note, and therefore those are not the least upper bounds.


问:
When should a private method take the public route to access private data?
When should a private method take the public route to access private data?
For example, if I had this immutable 'multiplier' class (a bit contrived, I know):

```<code>class Multiplier {
public:
    Multiplier(int a, int b) : a(a), b(b) { }
    int getA() const { return a; }
    int getB() const { return b; }
    int getProduct() const { /* ??? */ }
private:
    int a, b;
};
</code>```

There are two ways I could implement getProduct:

```<code>    int getProduct() const { return a * b; }
</code>```

or

```<code>    int getProduct() const { return getA() * getB(); }
</code>```

Because the intention here is to use the value of a, i.e. to get a, using getA() to implement getProduct() seems cleaner to me. I would prefer to avoid using a unless I had to modify it. My concern is that I don't often see code written this way, in my experience a * b would be a more common implementation than getA() * getB().

Should private methods ever use the public way when they can access something directly?

答:
It depends of the actual meaning of a, b and getProduct.

The purpose of getters is to be able to change the actual implementation while keeping the interface of the object the same. For example, if one day, getA becomes return a + 1;, the change is localized to a getter.

Real scenario cases are sometimes more complicated than a constant backing field assigned through a constructor associated with a getter. For instance, the value of the field may be computed or loaded from a database in the original version of the code. In the next version, caching may be added to optimize performance. If getProduct continues to use the computed version, it won't benefit from caching (or the maintainer will do the same change twice).

If it makes perfect sense for getProduct to use a and b directly, use them. Otherwise, use getters to prevent maintenance issues later.

Example where one would use getters:

class Product {
public:
    Product(ProductId id) : {
        price = Money.fromCents(
            data.findProductById(id).price,
            environment.currentCurrency
        )
    }

    Money getPrice() {
        return price;
    }

    Money getPriceWithRebate() {
        return getPrice().applyRebate(rebate); // ← Using a getter instead of a field.
    }
private:
    Money price;
}
```

<p>While for the moment, the getter doesn't contain any business logic, it is not excluded that the logic in the constructor will be migrated to the getter in order to avoid doing database work when initializing the object:</p>

<pre class="lang-cpp prettyprint-override"><code>class Product {
public:
    Product(ProductId id) : id(id) { }

    Money getPrice() {
        return Money.fromCents(
            data.findProductById(id).price,
            environment.currentCurrency
        )
    }

    Money getPriceWithRebate() {
        return getPrice().applyRebate(rebate);
    }
private:
    const ProductId id;
}
</code>```

Later, caching may be added (in C#, one would use Lazy<T>, making the code short and easy; I don't know if there is an equivalent in C++):

class Product {
public:
    Product(ProductId id) : id(id) { }

    Money getPrice() {
        if (priceCache == NULL) {
            priceCache = Money.fromCents(
                data.findProductById(id).price,
                environment.currentCurrency
            )

        return priceCache;
    }

    Money getPriceWithRebate() {
        return getPrice().applyRebate(rebate);
    }
private:
    const ProductId id;
    Money priceCache;
}
```

<p>Both changes were focused on the getter and the backing field, the remaining code being unaffected. If, instead, I had used a field instead of a getter in <code>getPriceWithRebate</code>, I would have to reflect the changes there as well.</p>

<p><strong>Example where one would probably use private fields:</strong></p>

<pre class="lang-cpp prettyprint-override"><code>class Product {
public:
    Product(ProductId id) : id(id) { }
    ProductId getId() const { return id; }
    Money getPrice() {
        return Money.fromCents(
            data.findProductById(id).price, // ← Accessing `id` directly.
            environment.currentCurrency
        )
    }
private:
    const ProductId id;
}
</code>```

The getter is straightforward: it is a direct representation of a constant (similar to C#'s readonly) field which is not expected to change in the future: chances are, ID getter will never become a computed value. So keep it simple, and access the field directly.

Another benefit is that the getId might be removed in the future if it appears that it is not used outside (like in the previous piece of code).

Body:
It depends of the actual meaning of a, b and getProduct.

The purpose of getters is to be able to change the actual implementation while keeping the interface of the object the same. For example, if one day, getA becomes return a + 1;, the change is localized to a getter.

Real scenario cases are sometimes more complicated than a constant backing field assigned through a constructor associated with a getter. For instance, the value of the field may be computed or loaded from a database in the original version of the code. In the next version, caching may be added to optimize performance. If getProduct continues to use the computed version, it won't benefit from caching (or the maintainer will do the same change twice).

If it makes perfect sense for getProduct to use a and b directly, use them. Otherwise, use getters to prevent maintenance issues later.

Example where one would use getters:

class Product {
public:
    Product(ProductId id) : {
        price = Money.fromCents(
            data.findProductById(id).price,
            environment.currentCurrency
        )
    }

    Money getPrice() {
        return price;
    }

    Money getPriceWithRebate() {
        return getPrice().applyRebate(rebate); // ← Using a getter instead of a field.
    }
private:
    Money price;
}

While for the moment, the getter doesn't contain any business logic, it is not excluded that the logic in the constructor will be migrated to the getter in order to avoid doing database work when initializing the object:

class Product {
public:
    Product(ProductId id) : id(id) { }

    Money getPrice() {
        return Money.fromCents(
            data.findProductById(id).price,
            environment.currentCurrency
        )
    }

    Money getPriceWithRebate() {
        return getPrice().applyRebate(rebate);
    }
private:
    const ProductId id;
}

Later, caching may be added (in C#, one would use Lazy<T>, making the code short and easy; I don't know if there is an equivalent in C++):

class Product {
public:
    Product(ProductId id) : id(id) { }

    Money getPrice() {
        if (priceCache == NULL) {
            priceCache = Money.fromCents(
                data.findProductById(id).price,
                environment.currentCurrency
            )

        return priceCache;
    }

    Money getPriceWithRebate() {
        return getPrice().applyRebate(rebate);
    }
private:
    const ProductId id;
    Money priceCache;
}

Both changes were focused on the getter and the backing field, the remaining code being unaffected. If, instead, I had used a field instead of a getter in getPriceWithRebate, I would have to reflect the changes there as well.

Example where one would probably use private fields:

class Product {
public:
    Product(ProductId id) : id(id) { }
    ProductId getId() const { return id; }
    Money getPrice() {
        return Money.fromCents(
            data.findProductById(id).price, // ← Accessing `id` directly.
            environment.currentCurrency
        )
    }
private:
    const ProductId id;
}

The getter is straightforward: it is a direct representation of a constant (similar to C#'s readonly) field which is not expected to change in the future: chances are, ID getter will never become a computed value. So keep it simple, and access the field directly.

Another benefit is that the getId might be removed in the future if it appears that it is not used outside (like in the previous piece of code).


答:
I would say that using the public methods would be preferable, if not for any other reason but to conform to DRY.

I know in your case, you have simple backing fields for your accessors, but you could have certain logic, e.g. lazy loading code, which you need to run  before the first time you use that variable.  Thus, you would want to call your accessors instead of directly referencing your fields.  Even though you don't have this in this case, it makes sense to stick to a single convention.  That way, if you ever make a change to your logic, you only have to change it in one place.

Body:
When should a private method take the public route to access private data?
For example, if I had this immutable 'multiplier' class (a bit contrived, I know):

```<code>class Multiplier {
public:
    Multiplier(int a, int b) : a(a), b(b) { }
    int getA() const { return a; }
    int getB() const { return b; }
    int getProduct() const { /* ??? */ }
private:
    int a, b;
};
</code>```

There are two ways I could implement getProduct:

```<code>    int getProduct() const { return a * b; }
</code>```

or

```<code>    int getProduct() const { return getA() * getB(); }
</code>```

Because the intention here is to use the value of a, i.e. to get a, using getA() to implement getProduct() seems cleaner to me. I would prefer to avoid using a unless I had to modify it. My concern is that I don't often see code written this way, in my experience a * b would be a more common implementation than getA() * getB().

Should private methods ever use the public way when they can access something directly?


答:
For a class this small, simplicity wins. I would just use a * b.

For something far more complicated, I would strongly consider using getA() * getB() if I wanted to clearly separate the "minimal" interface from all the other functions in the full public API. An excellent example would be std::string in C++. It has 103 member functions, but only 32 of them really need access to private members. If you had a class that complex, forcing all the "non-core" functions to consistently go through the "core API" could make the implementation a lot easier to test, debug, and refactor.

Title: When should a private method take the public route to access private data?


答:
Typically, you would use the variables directly. You expect to change all members when changing a class's implementation. Not using the variables directly simply makes it more difficult to correctly isolate the code that depends on them and makes it harder to read the member.

This is of course different if the getters implement real logic, in that case it depends on whether you need to utilize their logic or not.


问:
S3 image urls in database
I have an application where users will be able to upload multiple images for one Product (via something like Ryan Bates nested fields, so you'd click "Add Image", and a file upload would appear on the same page). I'm planning on using jQuery File Upload, and Amazon S3, and nested fields.

The thing I'm confused about, is how people usually associate many images with a single model.

For example, if for every Product, there can be many Images, how do I store the images to be associated with the Product?

I was thinking of having jQuery File Upload return the s3 url for each image. So if 10 images were uploaded, then 10 hidden fields were created for each image-url, which I then JSON serialize and store in the Product model?

But this doesn't seem like a pretty solution? What's a better method?

答:
It sounds to me like you 2 tables: a Product table, and an Image table.  The Image table will have a foreign key back to the Product table and will store the image URL.

This way, a single Product can have a bunch of Images.

```<code>     Product                           Image
    +-----------------+              +-----------+
    |ProductID        |<------------+| ImageID   |
    |ProductName      |              | ProductID |
    |... and so on ...|              | ImageURL  |
    |                 |              |           |
    +-----------------+              +-----------+
</code>```

(ImageID doesn't really matter much for this diagram)

Title: S3 image urls in database

Body:
It sounds to me like you 2 tables: a Product table, and an Image table.  The Image table will have a foreign key back to the Product table and will store the image URL.

This way, a single Product can have a bunch of Images.

     Product                           Image
    +-----------------+              +-----------+
    |ProductID        |<------------+| ImageID   |
    |ProductName      |              | ProductID |
    |... and so on ...|              | ImageURL  |
    |                 |              |           |
    +-----------------+              +-----------+

(ImageID doesn't really matter much for this diagram)


问:
Are exceptions as control flow considered a serious antipattern? If so, Why?
Back in the late 90's I worked quite a bit with a code base that used exceptions as flow control. It implemented a finite state machine to drive telephony applications.  Lately I am reminded of those days because I've been doing MVC web apps.

They both have Controllers that decide where to go next and supply the data to the destination logic. User actions from the domain of an old-school telephone, like DTMF tones, became parameters to action methods, but instead of returning something like a ViewResult, they threw a StateTransitionException.

I think the main difference was that action methods were void functions.  I don't remember all the things I did with this fact but I've been hesitant to even go down the road of remembering much because since that job, like 15 years ago, I never saw this in production code at any other job. I assumed this was a sign that it was a so-called anti-pattern.

Is this the case, and if so, why?

答:
As others have mentioned numerously, (e.g. in this Stack Overflow question), the principle of least astonishment will forbid that you use exceptions excessively for control flow only purposes. On the other hand, no rule is 100% correct, and there are always those cases where an exception is "just the right tool" - much like goto itself, by the way, which ships in the form of break and continue in languages like Java, which are often the perfect way to jump out of heavily nested loops, which aren't always avoidable.

The following blog post explains a rather complex but also rather interesting use-case for a non-local ControlFlowException:

http://blog.jooq.org/2013/04/28/rare-uses-of-a-controlflowexception

It explains how inside of jOOQ (a SQL abstraction library for Java) (disclaimer: I work for the vendor), such exceptions are occasionally used to abort the SQL rendering process early when some "rare" condition is met.

Examples of such conditions are:

Too many bind values are encountered. Some databases do not support arbitrary numbers of bind values in their SQL statements (SQLite: 999, Ingres 10.1.0: 1024, Sybase ASE 15.5: 2000, SQL Server 2008: 2100). In those cases, jOOQ aborts the SQL rendering phase and re-renders the SQL statement with inlined bind values. Example:

// Pseudo-code attaching a "handler" that will
// abort query rendering once the maximum number
// of bind values was exceeded:
context.attachBindValueCounter();
String sql;
try {

  // In most cases, this will succeed:
  sql = query.render();
}
catch (ReRenderWithInlinedVariables e) {
  sql = query.renderWithInlinedBindValues();
}
```

<p>If we explicitly extracted the bind values from the query AST to count them every time, we'd waste valuable CPU cycles for those 99.9% of the queries that don't suffer from this problem.</p></li>
<li><p>Some logic is available only indirectly via an API that we want to execute only "partially". The <code>UpdatableRecord.store()</code> method generates an <code>INSERT</code> or <code>UPDATE</code> statement, depending on the <code>Record</code>'s internal flags. From the "outside", we don't know what kind of logic is contained in <code>store()</code> (e.g. optimistic locking, event listener handling, etc.) so we don't want to repeat that logic when we store several records in a batch statement, where we'd like to have <code>store()</code> only generate the SQL statement, not actually execute it. Example:</p>

<pre class="lang-java prettyprint-override"><code>// Pseudo-code attaching a "handler" that will
// prevent query execution and throw exceptions
// instead:
context.attachQueryCollector();

// Collect the SQL for every store operation
for (int i = 0; i < records.length; i++) {
  try {
    records[i].store();
  }

  // The attached handler will result in this
  // exception being thrown rather than actually
  // storing records to the database
  catch (QueryCollectorException e) {

    // The exception is thrown after the rendered
    // SQL statement is available
    queries.add(e.query());
  }
}
</code>```

If we had externalised the store() logic into "re-usable" API that can be customised to optionally not execute the SQL, we'd be looking into creating a rather hard to maintain, hardly re-usable API.

Conclusion

In essence, our usage of these non-local gotos is just along the lines of what Mason Wheeler said in his answer:

"I just encountered a situation that I cannot deal with properly at this point, because I don't have enough context to handle it, but the routine that called me (or something further up the call stack) ought to know how to handle it."

Both usages of ControlFlowExceptions were rather easy to implement compared to their alternatives, allowing us to reuse a wide range of logic without refactoring it out of the relevant internals.

But the feeling of this being a bit of a surprise to future maintainers remains. The code feels rather delicate and while it was the right choice in this case, we'd always prefer not to use exceptions for local control flow, where it is easy to avoid using ordinary branching through if - else.

ContentLicense: CC BY-SA 4.0

Body:
As others have mentioned numerously, (e.g. in this Stack Overflow question), the principle of least astonishment will forbid that you use exceptions excessively for control flow only purposes. On the other hand, no rule is 100% correct, and there are always those cases where an exception is "just the right tool" - much like goto itself, by the way, which ships in the form of break and continue in languages like Java, which are often the perfect way to jump out of heavily nested loops, which aren't always avoidable.

The following blog post explains a rather complex but also rather interesting use-case for a non-local ControlFlowException:

http://blog.jooq.org/2013/04/28/rare-uses-of-a-controlflowexception

It explains how inside of jOOQ (a SQL abstraction library for Java) (disclaimer: I work for the vendor), such exceptions are occasionally used to abort the SQL rendering process early when some "rare" condition is met.

Examples of such conditions are:

Too many bind values are encountered. Some databases do not support arbitrary numbers of bind values in their SQL statements (SQLite: 999, Ingres 10.1.0: 1024, Sybase ASE 15.5: 2000, SQL Server 2008: 2100). In those cases, jOOQ aborts the SQL rendering phase and re-renders the SQL statement with inlined bind values. Example:

// Pseudo-code attaching a "handler" that will
// abort query rendering once the maximum number
// of bind values was exceeded:
context.attachBindValueCounter();
String sql;
try {

  // In most cases, this will succeed:
  sql = query.render();
}
catch (ReRenderWithInlinedVariables e) {
  sql = query.renderWithInlinedBindValues();
}

If we explicitly extracted the bind values from the query AST to count them every time, we'd waste valuable CPU cycles for those 99.9% of the queries that don't suffer from this problem.

Some logic is available only indirectly via an API that we want to execute only "partially". The UpdatableRecord.store() method generates an INSERT or UPDATE statement, depending on the Record's internal flags. From the "outside", we don't know what kind of logic is contained in store() (e.g. optimistic locking, event listener handling, etc.) so we don't want to repeat that logic when we store several records in a batch statement, where we'd like to have store() only generate the SQL statement, not actually execute it. Example:

// Pseudo-code attaching a "handler" that will
// prevent query execution and throw exceptions
// instead:
context.attachQueryCollector();

// Collect the SQL for every store operation
for (int i = 0; i < records.length; i++) {
  try {
    records[i].store();
  }

  // The attached handler will result in this
  // exception being thrown rather than actually
  // storing records to the database
  catch (QueryCollectorException e) {

    // The exception is thrown after the rendered
    // SQL statement is available
    queries.add(e.query());
  }
}

If we had externalised the store() logic into "re-usable" API that can be customised to optionally not execute the SQL, we'd be looking into creating a rather hard to maintain, hardly re-usable API.

Conclusion

In essence, our usage of these non-local gotos is just along the lines of what Mason Wheeler said in his answer:

"I just encountered a situation that I cannot deal with properly at this point, because I don't have enough context to handle it, but the routine that called me (or something further up the call stack) ought to know how to handle it."

Both usages of ControlFlowExceptions were rather easy to implement compared to their alternatives, allowing us to reuse a wide range of logic without refactoring it out of the relevant internals.

But the feeling of this being a bit of a surprise to future maintainers remains. The code feels rather delicate and while it was the right choice in this case, we'd always prefer not to use exceptions for local control flow, where it is easy to avoid using ordinary branching through if - else.


问:
Efficient algorithm to count number of substrings divisible by 3
Given a string of decimal digits, I have to find the number of all substrings divisible by 3 in the range L to R [both inclusive], where L & R are index[1-based] of the specified string

string length <= 100000

I've tried the Naive approach of iterating over all possible substrings & obtaining the answer, but that is not fast enough, especially for multiple pairs L & R.

Then I tried a DP approach. I can obtain all possible substrings divisible by 3 in the whole string, i.e. I'm unable to code the DP solution that gives result for given range.

DP Solution that I tried (not completely sure about It):

```<code>for(i=0 ; i<n ; i++) {
    for(j=0 ; j<3 ; j++) {
        dp[i][j]=0 ;
    }
    int curr = (input[i]-'0')%3 ;
    dp[i][curr]++ ;
    if(i) {
        for(j=0 ; j<3 ; j++) {
            if(curr % 3 == 0) { dp[i][j] += dp[i-1][j]; }
            if(curr % 3 == 1) { dp[i][j] += dp[i-1][(j+2)%3]; }
            if(curr % 3 == 2) { dp[i][j] += dp[i-1][(j+1)%3]; }
        }
    }
}
long long sum = 0;
for(i=0 ; i<n ; i++) { sum += dp[i][0] ; }
</code>```

Can this solution be modified to give results for given range [L,R] ?

After searching alot, I learnt that range queries problems are solved by Segment Tree, but I'm unsure as how Segment Tree + Lazy Propagation can help in this question.

So what is a performant way to count all substrings divisible by 3 in the range L to R [both inclusive]?

EDIT:

Input: First Line contains the given string. Lines after that contain two integers denoting L and R respectively, where both L and R are index(1-based) of string.

Input:

  301524
  1 2
  4 6
  3 5

Output:

  3
  1
  1

Explanation:

  When L=1 & R=2 we get 3 possible substrings, {3}, {0}, {30} & all these when considered as a decimal number are divisible by 3. Hence the output.

  When L=4 & R=6 we get 6 possible substrings, {5} , {52}, {524}, {2}, {24}, {4} & out of these only {24} is divisible by 3.

Repetitions in substrings like 3333 count multiple times, so for L=1 to R=4 the answer would be 10, since we have four times 3, three times 33, two times 333 and one time 3333 (all divisible by 3).

答:
We know A number is divisble by 3 if the sum of its digits is divisble by 3 (according to the divisibility rules of 3). There is O(n^2) dynamic programming solution (pre-processing) and O(1) constant time for each query.

Let arr[i] is array containing given elements (1....N) and query[i][j] denotes # of substrings divisible by 3 from [i, j]

```<code>for(int i = 1; i <= N; i++) {
    query[i][i] = (arr[i] % 3 == 0); // i.e. # of substrings divisible by 3 in [4, 4] is 1 if arr[4] is divisble by 3 otherwise 0
    arr[i] += arr[i - 1]; // arr[i] will contain cumulative sum of 1...i
}

//
for(int i = N - 1; i > 0; i--) {
    for(int j = i + 1; j <= N; j++) {
        // exclusion-inclusion principle. # of substrings in [1, 7] will be -
        // #1 sum of # of substrings in [1, 6] and [2, 7].
        //    As [2, 6] is included two times, so we need to subtract it one time
        // #2 plus 1 if substring [1, 7] is divisble by 3, 0 otherwise

        // #1
        query[i][j] = query[i][j - 1] + query[i + 1][j] - query[i + 1][j - 1];
        // #2
        // arr[j] contains sum of 1...j.
        // so arr[j] - arr[i - 1] contains sum of [i...j]
        // number constructed from substring [i...j] is divisble by 3
        // iff summation of its digits is divible by 3
        query[i][j] += ((arr[j] - arr[i - 1]) % 3 == 0);
    }
}
</code>```

Note: This will work when the # of elements (Range) is within 3 * 10^3. Otherwise the declation of query[Range][Range] will show compilation error.

If you still don't get what's happening on those loopings, use pen and paper to draw a 2D table and fill it up according to above calculation. Then you will surely get a clear intuition :)

Body:
We know A number is divisble by 3 if the sum of its digits is divisble by 3 (according to the divisibility rules of 3). There is O(n^2) dynamic programming solution (pre-processing) and O(1) constant time for each query.

Let arr[i] is array containing given elements (1....N) and query[i][j] denotes # of substrings divisible by 3 from [i, j]

for(int i = 1; i <= N; i++) {
    query[i][i] = (arr[i] % 3 == 0); // i.e. # of substrings divisible by 3 in [4, 4] is 1 if arr[4] is divisble by 3 otherwise 0
    arr[i] += arr[i - 1]; // arr[i] will contain cumulative sum of 1...i
}

//
for(int i = N - 1; i > 0; i--) {
    for(int j = i + 1; j <= N; j++) {
        // exclusion-inclusion principle. # of substrings in [1, 7] will be -
        // #1 sum of # of substrings in [1, 6] and [2, 7].
        //    As [2, 6] is included two times, so we need to subtract it one time
        // #2 plus 1 if substring [1, 7] is divisble by 3, 0 otherwise

        // #1
        query[i][j] = query[i][j - 1] + query[i + 1][j] - query[i + 1][j - 1];
        // #2
        // arr[j] contains sum of 1...j.
        // so arr[j] - arr[i - 1] contains sum of [i...j]
        // number constructed from substring [i...j] is divisble by 3
        // iff summation of its digits is divible by 3
        query[i][j] += ((arr[j] - arr[i - 1]) % 3 == 0);
    }
}

Note: This will work when the # of elements (Range) is within 3 * 10^3. Otherwise the declation of query[Range][Range] will show compilation error.

If you still don't get what's happening on those loopings, use pen and paper to draw a 2D table and fill it up according to above calculation. Then you will surely get a clear intuition :)


问:
Special parameters for behaviour, good or bad practice?
I really was questioning to myself where to ask this, as I could not decide myself. This is more of a software design question.

Context

I currently maintain a small Node.js module on NPM which basically acts as an API wrapper for an online service.

Issue

I have one function in the module which, when called with a string, makes one request to the service and receives the data, from a page, relevant to that one string input.

However, as a programmer and user of the service, I can understand that it might be useful to get the data for all possible input strings on that page. The way I have the module now, a programmer using my API wrapper would need to know every string, and call it every time, making a total of n requests, 1 for each string input, which is unacceptable if I'm trying to write a nice API wrapper for other developers (which I am).

* Possible Solutions/Question *

I thought to myself, I could write the function so that depending on the input string, if it's a special value (like null), I could retrieve all relevant data, but then I questioned whether this is good practice.

If I document the special input case nicely, is it good practice to have a specific parameter to a function which always produces a specific output? Is it better just to write another function that performs this procedure? I feel like having another function would violate the DRY principle because most of the code would be the same in the new function.

Thanks everyone! This really has bugged me for quite a while now.

答:
All of those are valid solutions, depending on what would be most intuitive to the users of your API.

If your users would expect getMagicData() to get all of the data by default, then do that, and let it accept an optional argument to specify a subset of the data.

But if that behavior would surprise and confuse your users, then make a separate getAllMagicData() method. It's not a DRY violation as long as both functions share the common code (either by making a third "private" method or by having getAllMagicData() simply call getMagicData() repeatedly).

Based solely on the description you've provided, I would probably find separate methods more intuitive.


问:
This way I'm writing this code is testable, but is there something wrong with it I'm missing?
I have an interface called IContext. For the purposes of this it doesn't really matter what's it does except the following:

```<code>T GetService<T>();
</code>```

What this method does is look at the current DI container of the application and attempts to resolve the dependency. Fairly standard I think.

In my ASP.NET MVC application, my constructor looks like this.

```<code>protected MyControllerBase(IContext ctx)
{
    TheContext = ctx;
    SomeService = ctx.GetService<ISomeService>();
    AnotherService = ctx.GetService<IAnotherService>();
}
</code>```

So rather than adding multiple parameters in the constructor for each service (because this will get really annoying and time-consuming for the developers extending the application) I am using this method to get services.

Now, it feels wrong. However, the way I'm currently justifying it in my head is this - I can mock it.

I can. It wouldn't be difficult to mock up IContext to test the Controller. I'd have to anyway:

```<code>public class MyMockContext : IContext
{
    public T GetService<T>()
    {
        if (typeof(T) == typeof(ISomeService))
        {
            // return another mock, or concrete etc etc
        }

        // etc etc
    }
}
</code>```

But as I said, it feels wrong. Any thoughts / abuse welcome.

答:
This design is known as Service Locator* and I don't like it. There are lots of arguments against it:

Service Locator couples you to your container. Using regular dependency injection (where the constructor spells out the dependencies explicitly) you can straightforwardly replace your container with a different one, or go back to new-expressions. With your IContext that's not really possible.

Service Locator hides dependencies. As a client, it's very difficult to tell what you need to construct an instance of a class. You need some sort of IContext, but you also need to set the context up to return the correct objects in order to make the MyControllerBase work. This is not at all obvious from the signature of the constructor. With regular DI the compiler tells you exactly what you need. If your class has a lot of dependencies, you should feel that pain because it will spur you to refactor. Service Locator hides the problems with bad designs.

Service Locator causes run-time errors. If you call GetService with a bad type parameter you'll get an exception. In other words, your GetService function is not a total function. (Total functions are an idea from the FP world, but it basically means that functions should always return a value.) Better to let the compiler help and tell you when you've got the dependencies wrong.

Service Locator violates the Liskov Substitution Principle. Because its behaviour varies based on the type argument, Service Locator can be viewed as if it effectively has an infinite number of methods on the interface! This argument is spelled out in detail here.

Service Locator is hard to test. You've given an example of a fake IContext for tests, which is fine, but surely it's better not to have to write that code in the first place. Just inject your fake dependencies directly, without going via your service locator.

In short, just don't do it. It seems like a seductive solution to the problem of classes with lots of dependencies, but in the long run you're just going to make your life miserable.

* I'm defining Service Locator as an object with a generic Resolve<T> method which is capable of resolving arbitrary dependencies and is used throughout the codebase (not just at the Composition Root). This is not the same as Service Facade (an object which bundles up some small known set of dependencies) or Abstract Factory (an object which creates instances of a single type - the type of an Abstract Factory may be generic but the method is not).


答:
Having one instead of many parameters in the constructor is not the problematic part of this design. As long as your IContext class is nothing but a service facade, specificially for providing the dependencies used in MyControllerBase, and not a general service locator used throughout your whole code, that part of your code is IMHO ok.

Your first example might be changed to

```<code>protected MyControllerBase(IContext ctx)
{
    TheContext = ctx;
    SomeService = ctx.GetSomeService();
    AnotherService = ctx.GetAnotherService();
}
</code>```

that would not be a substantial design change of MyControllerBase. If this design is good or bad depends only on the fact if your want to

make sure TheContext, SomeService and AnotherService are always all initialized with mock objects, or all of them with real objects

or, to allow initialization them with different combinations of the 3 objects (which means, for this case your would need to pass the parameters individually)

So using only one parameter instead of 3 in the constructor can be fully reasonable.

The thing which is problematic is IContext exposing the GetService method in public. IMHO you should avoid this, instead keep the "factory methods" explicit. So will it be ok to implement the GetSomeService and GetAnotherService methods from my example using a service locator? IMHO that depends. As long the IContext class keeps just beeing a simple abstract factory for the specific purpose of providing an explicit list of service objects, that is IMHO acceptable. Abstract factories are typically just "glue" code, which don't have to be unit-tested itself. Nethertheless you should ask yourself if in the context of methods like GetSomeService, if you really need a service locator, or if an explicit constructor call would not be simpler.

So beware, when you stick to a design where the IContext implementation is just a wrapper around a public, generic GetService method, allowing to resolve any arbitrary depencencies by arbitrary classes, then everything applies what @BenjaminHodgson wrote in his answer.

Title: This way I'm writing this code is testable, but is there something wrong with it I'm missing?

Body:
I have an interface called IContext. For the purposes of this it doesn't really matter what's it does except the following:

```<code>T GetService<T>();
</code>```

What this method does is look at the current DI container of the application and attempts to resolve the dependency. Fairly standard I think.

In my ASP.NET MVC application, my constructor looks like this.

```<code>protected MyControllerBase(IContext ctx)
{
    TheContext = ctx;
    SomeService = ctx.GetService<ISomeService>();
    AnotherService = ctx.GetService<IAnotherService>();
}
</code>```

So rather than adding multiple parameters in the constructor for each service (because this will get really annoying and time-consuming for the developers extending the application) I am using this method to get services.

Now, it feels wrong. However, the way I'm currently justifying it in my head is this - I can mock it.

I can. It wouldn't be difficult to mock up IContext to test the Controller. I'd have to anyway:

```<code>public class MyMockContext : IContext
{
    public T GetService<T>()
    {
        if (typeof(T) == typeof(ISomeService))
        {
            // return another mock, or concrete etc etc
        }

        // etc etc
    }
}
</code>```

But as I said, it feels wrong. Any thoughts / abuse welcome.

Body:
Having one instead of many parameters in the constructor is not the problematic part of this design. As long as your IContext class is nothing but a service facade, specificially for providing the dependencies used in MyControllerBase, and not a general service locator used throughout your whole code, that part of your code is IMHO ok.

Your first example might be changed to

protected MyControllerBase(IContext ctx)
{
    TheContext = ctx;
    SomeService = ctx.GetSomeService();
    AnotherService = ctx.GetAnotherService();
}

that would not be a substantial design change of MyControllerBase. If this design is good or bad depends only on the fact if your want to

make sure TheContext, SomeService and AnotherService are always all initialized with mock objects, or all of them with real objects

or, to allow initialization them with different combinations of the 3 objects (which means, for this case your would need to pass the parameters individually)

So using only one parameter instead of 3 in the constructor can be fully reasonable.

The thing which is problematic is IContext exposing the GetService method in public. IMHO you should avoid this, instead keep the "factory methods" explicit. So will it be ok to implement the GetSomeService and GetAnotherService methods from my example using a service locator? IMHO that depends. As long the IContext class keeps just beeing a simple abstract factory for the specific purpose of providing an explicit list of service objects, that is IMHO acceptable. Abstract factories are typically just "glue" code, which don't have to be unit-tested itself. Nethertheless you should ask yourself if in the context of methods like GetSomeService, if you really need a service locator, or if an explicit constructor call would not be simpler.

So beware, when you stick to a design where the IContext implementation is just a wrapper around a public, generic GetService method, allowing to resolve any arbitrary depencencies by arbitrary classes, then everything applies what @BenjaminHodgson wrote in his answer.


问:
What should I do when using Golomb/Rice code for large values？
When using Golomb/Rice code in image compression, it is inevitable for us to meet large values. Golomb coding uses a tunable parameter M to divide an input value N into two parts : q, the result of a division by M, and r, the remainder. The quotient is sent in unary coding, followed by the remainder in binary.

For example, if N is 120, and M is 4, then q is 30(in unary 111.....1111110, 31bits), r is 0. So the result is 33 bits. It is not practical in the use of image compression.

So what should I do when using Golomb/Rice code for large values?
Or does it have any rules for large values?

答:
I don't understand why "33 bits is not practical".  There's two answers to that depending on what you mean:

The whole point of this sort of encoding is to optimise
representation of the small values at the expense of large values.
Assuming a suitable distribution of numbers to be compressed with
many more smaller values than larger values, there should be less
bits needed by the encoded representation overall.  Note that for image
compression, this sort of scheme is generally used to encode errors
from a predicted pixel value, not the pixel values themselves.

If you're referring to some issue due to a 32 bit integer size in the language you're using, I find it's quite important/useful to have an nice arbitrary length bitvector class for this sort of thing (boost's dynamic_bitset for example).


答:
Golomb-Codes and Rice-Codes are only efficient, if the Symbols you want to encode have a geometric distribution or near geometric distribution. ( d(n)=(1-p) pn ). This is a code which can encode even infinite values, but the encoded symbol grows in size when further away from 0, since they are less probable than values near 0. This is why you spend more bits on less probable symbols and few bits on very probable symbols.

A Golomb code is a variable length code. Where each symbol could be encoded at different legth. The less probable, the longer the encoding. Each symbol is encoded by multiple bits and you write the encoding bit by bit, regardless if you encountered a magic 8, 16, 32, or 64 bit bound. The code is not meant to be read/written byte, word, int or long, this is what you do, when writing the encoded data to the disk. If you must spend 33 bits for a given symbol, you must spend it, otherwise the code is not reversible. But you must read or write bitwise.

In your example the value 120 would create a 31 bit prefix and some extrabits 2 for the code. But on the other hand 120 is 2-30 times less probable than 0. Thus it is completely perfect to spend this "much" bits for it.

The selection of the optimal M depends on the given distribution. Golomb-Coding and Rice-Coding (which is a special case of Golomb coding) are used in image compression and video compression, because it is easy to implement and is fast in processing.

Title: What should I do when using Golomb/Rice code for large values？

Body:
When using Golomb/Rice code in image compression, it is inevitable for us to meet large values. Golomb coding uses a tunable parameter M to divide an input value N into two parts : q, the result of a division by M, and r, the remainder. The quotient is sent in unary coding, followed by the remainder in binary.

For example, if N is 120, and M is 4, then q is 30(in unary 111.....1111110, 31bits), r is 0. So the result is 33 bits. It is not practical in the use of image compression.

So what should I do when using Golomb/Rice code for large values?
Or does it have any rules for large values?


问:
If you could only have one programming related book on your bookshelf what would it be and why?
One per answer please. I'll add my favourite as an answer.</p>

答: The C++ Programming Language by Bjarne Stroustrup

ContentLicense: CC BY-SA 2.5


问:
int * vs int [N] vs int (*)[N] in functions parameters. Which one do you think is better?
When programming in C (or C++) there are three different ways to specify the parameter in a function that takes an array.

Here is an example (implementing std::accumulate from C++ in C) that shows you what I mean.

I can write it like this:

```<code>int accumulate(int n, int *array)
{
    int i;
    int sum = 0;
    for (i = 0; i < n; ++i) {
        sum += array[i];
    }
    return sum;
}
</code>```

This can also be written to this (which means the very same thing):

```<code>int accumulate(int n, int array[])
{
    int i;
    int sum = 0;
    for (i = 0; i < n; ++i) {
        sum += array[i];
    }
    return sum;
}
</code>```

I can also write it like this:

```<code>int accumulate(int n, int (*array)[])
{
    int i;
    int sum = 0;
    for (i = 0; i < n; ++i) {
        sum += (*array)[i];
    }
    return sum;
}
</code>```

All these options are very similar and generate the same executable code but they have a slight difference which is how the caller passes the arguments.

This is how the first two options gets called:

```<code>int main(void)
{
    int a[] = {3, 4, 2, 4, 6, 1, -40, 23, 35};
    printf("%d\n", accumulate(ARRAY_LENGTH(a), a));
    return 0;
}
</code>```

This is how the thrid option gets called:

```<code>int main(void)
{
    int a[] = {3, 4, 2, 4, 6, 1, -40, 23, 35};
    printf("%d\n", accumulate(ARRAY_LENGTH(a), &a));
    return 0;
}
</code>```

Note that the third option requires to user to explicitly specify the address of a
with &a. The first two options does not require this because arrays implicitly gets converted into pointers to the same type in C.

I have always preferred the third approach.

This is why:

It is more consistent with how other types are passed by pointers.

```<code>int draw_point(struct point *p);

int main()
{
    struct point p = {3, 4};
    draw_point(&p); // Here is the 'address of' operator required.
}
</code>```

It makes it possible to use macros like ARRAY_LENGTH to get the amount of elements in the array.

```<code>#include <stdio.h>
#define ARRAY_LENGTH(A) (sizeof(A) / sizeof(A[0]))

void this_works(int (*array)[10])
{
    /* This works! */
    printf("%d\n", ARRAY_LENGTH(*array));
}

void this_is_invalid_and_dangerous(int array[10])
{
    /* This does NOT work because `array` is actually a pointer. */
    printf("%d\n", ARRAY_LENGTH(array));
}
</code>```

The only advantage I see with int array[] (and int *array) is that you get to write array[X] instead of (*array)[X] when you wish to grab an index.

What are your professional thoughts on this? Which approach do you think is better and why? Do you ever mix the two? If so when do you choose what?

Like I said have I always preferred using int (*array)[N] but I see that the other two approaches are quite common as well.

答:
In practice, you'll see

```<code>int accumulate( int n, int *array)
</code>```

most often.  It's the most flexible (it can handle arrays of different sizes) and most closely reflects what's happening under the hood.

You won't see

```<code>int accumulate( int (*array)[N] )
</code>```

as often, since it assumes a specific array size (the size must be specified).

If your compiler supports variable-length array syntax, you could do

```<code>int accumulate( size_t n, int (*array)[n] )
</code>```

but I don't know how common that is.

Body:
In practice, you'll see

int accumulate( int n, int *array)

most often.  It's the most flexible (it can handle arrays of different sizes) and most closely reflects what's happening under the hood.

You won't see

int accumulate( int (*array)[N] )

as often, since it assumes a specific array size (the size must be specified).

If your compiler supports variable-length array syntax, you could do

int accumulate( size_t n, int (*array)[n] )

but I don't know how common that is.


问:
How do I avoid cascading refactorings?
I've got a project. In this project I wished to refactor it to add a feature, and I refactored the project to add the feature.

The problem is that when I was done, it turned out that I needed to make a minor interface change to accommodate it. So I made the change. And then the consuming class can't be implemented with its current interface in terms of the new one, so it needs a new interface as well. Now it's three months later, and I've had to fix innumerable virtually unrelated problems, and I'm looking at solving issues that were roadmapped for a year from now or simply listed as won't fix due to difficulty before the thing will compile again.

How can I avoid this kind of cascading refactorings in the future? Is it just a symptom of my previous classes depending too tightly on each other?

Brief edit: In this case, the refactor was the feature, since the refactor increased the extensibility of a particular piece of code and decreased some coupling. This meant that external developers could do more, which was the feature I wanted to deliver. So the original refactor itself should not have been a functional change.

Bigger edit that I promised five days ago:

Before I began this refactor, I had a system where I had an interface, but in the implementation, I simply dynamic_cast through all the possible implementations that I shipped. This obviously meant that you couldn't just inherit from the interface, for one thing, and secondly, that it would be impossible for anybody without implementation access to implement this interface. So I decided that I wanted to fix this issue and open up the interface for public consumption so that anybody could implement it and that implementing the interface was the entire contract required- obviously an improvement.

When I was finding and killing-with-fire all the places that I had done this, I found one place that proved to be a particular problem. It depended upon implementation details of all the various deriving classes and duplicated functionality that was already implemented but better somewhere else. It could have been implemented in terms of the public interface instead and re-used the existing implementation of that functionality. I discovered that it required a particular piece of context to function correctly. Roughly speaking, the calling previous implementation looked kinda like

```<code>for(auto&& a : as) {
     f(a);
}
</code>```

However, to get this context, I needed to change it into something more like

```<code>std::vector<Context> contexts;
for(auto&& a : as)
    contexts.push_back(g(a));
do_thing_now_we_have_contexts();
for(auto&& con : contexts)
    f(con);
</code>```

This means that for all operations that used to be a part of f, some of them need to be made a part of the new function g that operates without a context, and some of them need to be made of a part of the now-deferred f. But not all methods f call need or want this context- some of them need a distinct context that they obtain through separate means. So for everything that f ends up calling (which is, roughly speaking, pretty much everything), I had to determine what, if any, context they needed, where they should get it from, and how to split them from old f into new f and new g.

And that's how I ended up where I am now. The only reason that I kept going is because I needed this refactoring for other reasons anyway.

答:
Automated tests. You don't need to be a TDD zealot, nor do you need 100% coverage, but automated tests are what allow you to make changes confidently. In addition, it sounds like you have a design with very high coupling; you should read about the SOLID principles, which are formulated specifically to address this kind of issue in software design.

I'd also recommend these books.

Working Effectively with Legacy Code, Feathers

Refactoring, Fowler

Growing Object-Oriented Software, Guided by Tests, Freeman and Pryce

Clean Code, Martin

Title: How do I avoid cascading refactorings?


答:
You say that there are 3 ways in C and C++, but C++ actually makes a fourth available:

```<code>template<std::size_t n>
void arrayFunction(std::array<int,n> &array)
{ ...}
</code>```

This has several advantages over the solutions you suggest:

The parameter for the size of the array will be automatically determined on use by the compiler, meaning you don't have to specify it

The size is a compile time constant, meaning that the compiler can perform many optimizations that are impossible for the versions you suggest

It is impossible to specify an incorrect size, as the size is part of the type of the array

Title: int * vs int [N] vs int (*)[N] in functions parameters. Which one do you think is better?

Body:
When programming in C (or C++) there are three different ways to specify the parameter in a function that takes an array.

Here is an example (implementing std::accumulate from C++ in C) that shows you what I mean.

I can write it like this:

```<code>int accumulate(int n, int *array)
{
    int i;
    int sum = 0;
    for (i = 0; i < n; ++i) {
        sum += array[i];
    }
    return sum;
}
</code>```

This can also be written to this (which means the very same thing):

```<code>int accumulate(int n, int array[])
{
    int i;
    int sum = 0;
    for (i = 0; i < n; ++i) {
        sum += array[i];
    }
    return sum;
}
</code>```

I can also write it like this:

```<code>int accumulate(int n, int (*array)[])
{
    int i;
    int sum = 0;
    for (i = 0; i < n; ++i) {
        sum += (*array)[i];
    }
    return sum;
}
</code>```

All these options are very similar and generate the same executable code but they have a slight difference which is how the caller passes the arguments.

This is how the first two options gets called:

```<code>int main(void)
{
    int a[] = {3, 4, 2, 4, 6, 1, -40, 23, 35};
    printf("%d\n", accumulate(ARRAY_LENGTH(a), a));
    return 0;
}
</code>```

This is how the thrid option gets called:

```<code>int main(void)
{
    int a[] = {3, 4, 2, 4, 6, 1, -40, 23, 35};
    printf("%d\n", accumulate(ARRAY_LENGTH(a), &a));
    return 0;
}
</code>```

Note that the third option requires to user to explicitly specify the address of a
with &a. The first two options does not require this because arrays implicitly gets converted into pointers to the same type in C.

I have always preferred the third approach.

This is why:

It is more consistent with how other types are passed by pointers.

```<code>int draw_point(struct point *p);

int main()
{
    struct point p = {3, 4};
    draw_point(&p); // Here is the 'address of' operator required.
}
</code>```

It makes it possible to use macros like ARRAY_LENGTH to get the amount of elements in the array.

```<code>#include <stdio.h>
#define ARRAY_LENGTH(A) (sizeof(A) / sizeof(A[0]))

void this_works(int (*array)[10])
{
    /* This works! */
    printf("%d\n", ARRAY_LENGTH(*array));
}

void this_is_invalid_and_dangerous(int array[10])
{
    /* This does NOT work because `array` is actually a pointer. */
    printf("%d\n", ARRAY_LENGTH(array));
}
</code>```

The only advantage I see with int array[] (and int *array) is that you get to write array[X] instead of (*array)[X] when you wish to grab an index.

What are your professional thoughts on this? Which approach do you think is better and why? Do you ever mix the two? If so when do you choose what?

Like I said have I always preferred using int (*array)[N] but I see that the other two approaches are quite common as well.

Body:
You say that there are 3 ways in C and C++, but C++ actually makes a fourth available:

template<std::size_t n>
void arrayFunction(std::array<int,n> &array)
{ ...}

This has several advantages over the solutions you suggest:

The parameter for the size of the array will be automatically determined on use by the compiler, meaning you don't have to specify it

The size is a compile time constant, meaning that the compiler can perform many optimizations that are impossible for the versions you suggest

It is impossible to specify an incorrect size, as the size is part of the type of the array


问:
Are there open-source JavaScript libraries addressing multiple browser tabs and client state for newer browsers?
There are a few new HTML5 features that have made it into recent browsers that allow sharing state among tabs, browser windows, same domain windows, etc. So it's probably gotten a little easier to write a web application that keeps a lot of state on the client and also manages state intelligently between tabs and/or windows.

There are currently libraries like Backbone.js that can help manage state in a single tab or a single window. Is there anything out there yet that helps with multiple tabs (or windows) managing global state, tab specific state, and cross-tab eventing without relying on the server to sync them all up?

答:
If your windows (pages) are from the same domain (origin), localStorage can be used to share data and to  broadcast messages. One thing you should consider is that each browser window (page) works in a separate thread. So, if we are talking about cross-window communication, we are also talking about multithreading.

You should also consider some localStorage issues with IE:

I've performed some tests for localStorage in IE8. After several thousands of changes to localStorage, windows from the same origin stop receiving 'storage' events. Even more, then you try to read from the same localStorage item, values may be differrent in different windows. So, I'd say that IE8 doesn't support localStorage

IE9 and IE10 call 'storage' event handler even if localStorage is changed from this window (this is against specification).

There are also known issues with IE11.

I've recently published the interwindow communication library (all features are described in readme). It provides thread-safe data sharing, event broadcasting. It also solves some IE issues (IE8 definitely is not supported, IE11 bug with iframe inside different origin parent may be solved only by IE fixing - waiting for IE11 update).


问:
Which components/phases of a JIT compiler are different from a traditional ahead of time compiler?
Besides a faster register allocation algorithm and some trade-off in control and data-flow analysis for optimization purposes, which components/phases of a JIT compiler are different from a traditional ahead of time compiler?</p>

答:
Since that is a very broad question, I'll stick to conceptual differences rather than implementation details:

A JIT compiler can theoretically perform more platform-specific optimizations, since it doesn't have to worry about producing a binary that's compatible with as many machines as possible.

A JIT compiler has access to some information only available at runtime, which means it can do things like make an optimized integer-only version of your function because it's only seen integer arguments so far (this makes it good for dynamic languages), or try to use less memory because your system doesn't have much left.

An AOT compiler never needs to be installed on your users' machines. A JIT compiler (and the runtime or VM it usually comes with) needs to be there every time they run a program using it.

An AOT compiler typically looks at your entire program, or at least very large portions of it, allowing it to do things like check for type errors across modules (which is good in static languages that rigidly define the types each function will accept) and remove code it knows will never be called.

Because AOT compilation only happens once, the executable's performance is more predictable and repeatable, even in situations when a JIT may perform better on average.


问:
Adding a graphical view to a system
I currently have an program in Java that simulates railway movements. Essentially, trains arrive on platforms, pick up and drop off passengers, and then proceed, respecting signalling where possible. However, currently this only exists in the program's state, and there is no actual graphical view of all of this happening.

It would be much more useful if one could see a diagram of the railway track and where trains were on it. To do this, everything now has to have (x, y) coordinates in respect of the JPanel so that they can be drawn. There are probably other useful fields and methods that would be useful in terms of depicting the current state.

I see two principal options:

Just throwing everything into the original classes. However, I don't like this since it's not a property of a train that it exists at (2, 3) on an arbitrary JPanel, that just happens to be a representation.

Creating a Visualizer class for every class that needs to be drawn, so there would be a TrainVisualizer class, a PlatformVisualizer class, etc., and all of these classes would inherit from a generic Visualizer class that would handle coordinates and such. The problem with this is that every time I create something, I basically have to create both the original thing (i.e. the Train), and the visualizer. This seems like the MVC pattern, but I've never quite understood it, and it does seem a bit unideal to have to have two classes for pretty much everything.

What would be the best way of adding this on to the existing program?

答:
At design level you have a couple of options:

Every now and then redraw the entire world

Redraw the entire world when it has changed

Every now and then check whether or not the world has changed. If so redraw the entire world.

If something changes, redraw the affected parts of the world

Every now and then check for changes and only redraw the affected parts of the world.

Every option has its positive and negative effects:

Redrawing the entire world saves time spent on figuring out the affected areas.

Redrawing parts of the world saves time spent on rendering

Redrawing with every change will give fast feedback to the viewer

Redrawing batched changes will accumulate changes in the same area and draw them in one go.

The way to select one of these options is to figure out (first a guess, later measuring) the size of the world, the number of changes, time spent on rendering, time needed for calculations, minimal required lag/frame rate.

It is not that hard to build them all the only thing that might have a huge impact is a notification per change/area as it will involve a lot of signaling between Model and View.

I'd go for full screen redraw every now and then and see if that is good enough because that is easiest to implement.

If it doesn't suffice, make it smarter.

Full screen drawing could be implemented by a Visitor that visits the world structure (or a copy of it that represents a moment in time) and paints it.

For area painting you could do something similar. There is no need to put all the drawing code in the Model, that is the job of the View.

Title: Adding a graphical view to a system


问:
How to comply with LGPL 2.1 source-code request?
I have an iOS app that uses the VLCKit framework for it's video player function. Today I got an email from the creator of VLC and in the email is stated this:

According to the LGPLv2.1 VLCKit and libvlc are licensed under, I hearby request the source code for our libraries.

Of course I want to comply with this request but what I'm not entirely sure about is what I should comply with. He wants the source code to his own libraries. Obviously he would already have the source code to his own library so I'm assuming there's some other purpose in him asking this. Is it to see if I have modified/changed it in any way? I haven't so, do I zip up the source files that I downloaded from his website last year and send them to him in an email? My app already does have a link to the source-code on VLC's website in the help/about section. I thought this was sufficient.

答:
Your question appears to have two parts:

How to comply with an LGPL backed source request.

Why the authors of a library you included would request their own source.

Source distribution mechanics

The first question is pretty mechanical and fairly straightforward.  Namely: tar / zip up the files that were used and send them to the requestor.  It makes no difference who the requesting person is.  You provide the source, as requested.

If you were providing the source via FTP, you could verify the FTP repository was working and have them retrieve the source from there.  It's possible that not all variations of the GPL1 licenses will support that approach.

The safest version for distribution or conveyance is directly sending the source.

Rationale of request from library author

Part of providing Free software (that's "Free as in Freedom" means following up and making sure that downstream consumers of the Free software are also complying with the terms of the license.

It's one thing to put up an FTP link or provide a disclaimer of "source available upon request".  But it's another level to actually verify that the FTP links do provide the source or that the source is actually available when requested.

It sounds like the creator of the library you used wanted to verify that you were complying with the terms of the license.  They (obviously) didn't need their own source code back.  They may have been concerned that you made modifications without re-releasing them, too.  Given the size of VLCkit, I don't think that was the case.  The most likely answer then is they want to make sure you're complying with the terms of the *GPL1 licensing that was used.

And based upon your follow-up comment:

I asked and he replied. Just zip up the source that I used and send it to him. No problem.

It sounds like they were making sure that you were doing your part in the Free software movement.

1 I'm writing under the presumption that other packages were used that were also either LGPL, AGPL, or GPL licensed.


答:
Is it just a symptom of my previous classes depending too tightly on each other?

Sure. One change causing a myriad of other changes is pretty much the definition of coupling.

How do I avoid cascading refactors?

In the worst sort of codebases, a single change will continue to cascade, eventually causing you to change (almost) everything. Part of any refactor where there is widespread coupling is to isolate the part you're working on. You need to refactor not just where your new feature is touching this code, but where everything else touches that code.

Usually that means making some adapters to help the old code work with something that looks and acts like the old code, but uses the new implementation/interface. After all, if all you do is change the interface/implementation but leave the coupling you're not gaining anything. It's lipstick on a pig.

Title: How do I avoid cascading refactorings?

Body:
I've got a project. In this project I wished to refactor it to add a feature, and I refactored the project to add the feature.

The problem is that when I was done, it turned out that I needed to make a minor interface change to accommodate it. So I made the change. And then the consuming class can't be implemented with its current interface in terms of the new one, so it needs a new interface as well. Now it's three months later, and I've had to fix innumerable virtually unrelated problems, and I'm looking at solving issues that were roadmapped for a year from now or simply listed as won't fix due to difficulty before the thing will compile again.

How can I avoid this kind of cascading refactorings in the future? Is it just a symptom of my previous classes depending too tightly on each other?

Brief edit: In this case, the refactor was the feature, since the refactor increased the extensibility of a particular piece of code and decreased some coupling. This meant that external developers could do more, which was the feature I wanted to deliver. So the original refactor itself should not have been a functional change.

Bigger edit that I promised five days ago:

Before I began this refactor, I had a system where I had an interface, but in the implementation, I simply dynamic_cast through all the possible implementations that I shipped. This obviously meant that you couldn't just inherit from the interface, for one thing, and secondly, that it would be impossible for anybody without implementation access to implement this interface. So I decided that I wanted to fix this issue and open up the interface for public consumption so that anybody could implement it and that implementing the interface was the entire contract required- obviously an improvement.

When I was finding and killing-with-fire all the places that I had done this, I found one place that proved to be a particular problem. It depended upon implementation details of all the various deriving classes and duplicated functionality that was already implemented but better somewhere else. It could have been implemented in terms of the public interface instead and re-used the existing implementation of that functionality. I discovered that it required a particular piece of context to function correctly. Roughly speaking, the calling previous implementation looked kinda like

```<code>for(auto&& a : as) {
     f(a);
}
</code>```

However, to get this context, I needed to change it into something more like

```<code>std::vector<Context> contexts;
for(auto&& a : as)
    contexts.push_back(g(a));
do_thing_now_we_have_contexts();
for(auto&& con : contexts)
    f(con);
</code>```

This means that for all operations that used to be a part of f, some of them need to be made a part of the new function g that operates without a context, and some of them need to be made of a part of the now-deferred f. But not all methods f call need or want this context- some of them need a distinct context that they obtain through separate means. So for everything that f ends up calling (which is, roughly speaking, pretty much everything), I had to determine what, if any, context they needed, where they should get it from, and how to split them from old f into new f and new g.

And that's how I ended up where I am now. The only reason that I kept going is because I needed this refactoring for other reasons anyway.


问:
Constructor vs casting operator
I'm programming a library (so I have complete access to all the mentioned classes). Two classes (A and B) are essentially the same and differ only by their implementation, so they can easily be converted into one another.
But I'm asking myself, if converting by passing an argument of type B to one of A's constructors or by implicitly casting B into A, is preferable. Two code examples to illustrate:

Using casting:

```<code>class A
{
public:
    int c[3];
    operator B() const
    {
        //return B(...);
    }
};

class B
{
public:
    int a, b, c;
    operator A() const
    {
        //return A(...);
    }
};
</code>```

Using the constructor:

```<code>class A
{
public:
    A(const B& b)
    {
        //...
    }
    int c[3];
};

class B
{
public:
    B(const A& a)
    {
        //...
    }
    int a, b, c;
};
</code>```

What are the pros and cons of both approaches? Which should one use? And could there be some problems, if someone extended the library and used the explicit keyword in some of his constructors?

答:
The common way to perform such conversions is through the constructor. The typecast operators are used effectively only for conversions to primitive types (and then mostly to bool or something that effectively acts like a boolean) or types that you can't add an additional constructor to.

The typecast operators have a much bigger risk of being invoked at unexpected moments than converting constructors and should generally be treated with extreme caution.

Title: Constructor vs casting operator


答:
Most of the JIT compilers take an intermediate or bytecode language as their input. For that reason, the structure of a JIT compiler is closer to that of a traditional assembler than that of an AOT compiler.

Lexical analysis and parsing are much simpler, because the input language is much simpler that your typical high level programming language.

Semantic analysis is probably completely absent, trusting that the bytecode doesn't try to do the impossible (like mixing integer and floating point operations without the required conversions).

What a AOT and JIT compiler have in common are the optimisations and code generation, although a JIT compiler can't perform lengthy optimisations but can easily do optimisations that require information about how the code is actually being used.

Title: Which components/phases of a JIT compiler are different from a traditional ahead of time compiler?

Body: Besides a faster register allocation algorithm and some trade-off in control and data-flow analysis for optimization purposes, which components/phases of a JIT compiler are different from a traditional ahead of time compiler?</p>


问:
Should you test development features?
Is it a good practice to test features that only run in a development environment, or just a waste of time?

Specifics: The item that is prompting this question is a line of code that dynamically re-compiles style sheets. For production it compiles them once, then puts them in ./build/. As for research, I did some googling, but couldn't find anything. I am new to testing, so I might just not be looking right.

答:
I would say this depends on what you call a "development feature".

Unit tests or other automatic tests could be called "development features". Testing them separately does not make sense. In fact, you "test" them every time you run them.

"Debugging tools" - maybe, if they are important to your team and you think someone could accidentally break them.

features which are currently only active in your development environment, but could become production features in the future - probably yes.

code generation tools: this depends on what happens with the generated code. If there is a syntax check for the generated code (for example by a compiler), and a semantic check - for example by unit tests for the generated code- then it may be safe enough not to test the generator separately. One could argue the unit tests for the generated code are also tests for the code generator. But in fact, if a separate test makes sense depends on the complexity of the generator, how often the generator is subject to change, and how hard it gets to find the root cause of potential bugs without separate tests. This former SO question also dealt with the question of how to unit test a code generator.

Title: Should you test development features?


答:
It sound like your refactoring was too ambitious. A refactoring should be applied in small steps, each of which can be completed in (say) 30 minutes - or, in a worst-case scenario, at most a day - and leaves the project buildable and all tests still passing.

If you keep each individual change minimal, it really shouldn't be possible for a refactoring to break your build for a long time. The worst case is probably changing the parameters to a method in a widely used interface, e.g. to add a new parameter.  But the consequential changes from this are mechanical: adding (and ignoring) the parameter in each implementation, and adding a default value in each call.  Even if there are hundreds of references, it shouldn't take even a day to perform such a refactoring.

Title: How do I avoid cascading refactorings?


问:
What are some hashmaps we can easily implement?
At many places, I read that we can use HashMap here for O(1) search. Actually, I want to ask how I can implement easy hashmaps which can satisfy this property. Can anyone tell few hashmaps including collision thing into consideration.

I don't want complete codes. I want just pseudo code or algorithm for this. I am curious to know thing thing because I read this hashmaps use a lot and at many places. Thanks a lot in advance.

答:
To keep collisions at a minimum, there are two big things you definitely need to get right:

The hashmap's size must be sufficient to fit most or all of the data without collisions. Of course, you can have a hashmap that dynamically resizes itself after seeing a lot of collisions; you should still get O(1) amortized as long as this doesn't happen too often.

The hash function must be good enough to make collisions a rare occurrence on your data set. The properties of your data are very important here, but for a detailed list of general options, see this existing PSE question. The short answer seems to be "use FNV-1a".

Also, here are some dead-simple code samples to help get you started.


问:
How to write unit tests for a piece of code that has a data context?
I am new to unit testing and using Microsoft's unit testing library for following piece of code. When I execute the code normally it executes fine, however when I run unit test written for this code I get a nullreference error at the point of datacontext initialization.

Following is a method similar to the one i am trying to test:

```<code>    public int DeleteXYZTableRecord(int Id)
    {
        try
        {
            int XYZTableIdDeleted = -1;
            using (System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required,
                                                           new System.Transactions.TransactionOptions { IsolationLevel =  System.Transactions.IsolationLevel.Snapshot }))
            {
                if (Id <= 0)
                {
                    throw new ArgumentException(InvalidIdMessage);
                }
                using (DBDataContext context = new DBDataContext()) //**exception occurs here**
                {//block inside using is irrelevant as its never executed due to the exception
                    XYZTable modifiedXYZRecord = context .XYZTables.Where(x => x.ID.Equals(Id)).FirstOrDefault();
                    if (modifiedXYZRecord == null)
                        throw new NullReferenceException(RecordNotFoundMessage);

                    if (modifiedXYZRecord .pqrRecords == null && modifiedXYZRecord .pqrRecords == null)
                    {
                        modifiedXYZRecord .status = 0;
                        context.SubmitChanges();
                        XYZTableIdDeleted = modifiedXYZRecord .ID;
                    }

                }
                scope.Complete();
            }
            return XYZTableIdDeleted ;
        }
        catch (Exception)
        {

            throw;
        }

    }
</code>```

And here's the test method I am using to test it:

```<code>    [TestMethod]
    public void DeleteXYZTest()
    {

        string exceptionName = String.Empty;

        try
        {

            var target = new DBService.UpdateData .XYZDBHandler();

            // Access the data
            int inputId = 1;
            int expectedOutputId = 1;

            int actual = target.DeleteXYZTableRecord(inputId);
            Assert.AreEqual(expectedOutputId, actual,
                "x:<{0}> y:<{1}>",
                new object[] { expectedOutputId, actual });
        }
        catch (Exception e)
        {
            StringAssert.Contains(e.Message, DBService.UpdateData.XYZDBHandler.RecordNotFoundMessage);

            return;
        }
        Assert.Fail("No exception was thrown.");
    }
</code>```

答:
In order for unit tests to work you have to be able to mock all the external dependencies to your code (otherwise you're doing an integration test). Your problem is you have direct dependencies to your data access implementations. This is coupled with the problem that your handler is both doing its handling work and is responsible for creating your data access classes.

What you want to be doing is abstracting your data layer. This is most often done with what's called Repository pattern. It doesn't have to be, but the point is you need a layer of abstraction between your handler and your data access. Then generally you would pass this dependency in from the thing that's calling the handler. This is most often achieved with dependency injection frameworks, but again, you don't necessarily need to go that far.

Once you no longer have a dependency on a concrete class, you can use a mocking framework to mock the data access dependencies. Try Rhino or Moq, there's a lot of different ones. You would mock the interface you send into the handler, and specify what the handler does when you call it. This removes the variability of what your dependencies do and let's you focus solely on the functionality of the code you're testing.


问:
Entry point constructor vs init(),run() etc
Lets suppose we have some Js Widget, that includes three objects view, controller, model.

```<code>var MyWidget=function(){
 this.setModel(new Model());
 this.setView(new View());
 this.setController(new Controller());
 ...
}
</code>```

And I create this widget this way widget=new MyWidget();

There must be some enty point to start this widget.My question is - what is the best practise (and why) to define entry point: in constructor or in some method (run,init,etc). I mean:

```<code>widget=new MyWidget(); //to create AND start widget
</code>```

vs

```<code>widget=new MyWidget() //to create
widget.run();  //to start
</code>```

答:
Would there ever be a purpose to creating your widget without "starting" it? If not, just do it all in the constructor. If there is a purpose, but it's uncommon, consider some alternatives like using a separate class with an init/run function so that the default use case remains as simple as possible. If the purpose is common, then having an init/run function is fine.

When it comes to APIs, always try to make the most common use cases the easiest ones to get right.


问:
Testing - How to test if you are actually testing the code?
I was thinking about unit tests and code coverage, and I came up with this thought:

It is possible to have 100% code coverage and not test 100% of your code.

For example:

```<code>function myTestedFunction(){
    doSomething();
    doSomethingElse();
}
</code>```

In this example, if I have a  test that myTestedFunction calls doSomething, doSomethingElse(); will count as tested, even though it's not. Is there some way or library that will run your tests with each line removed? I feel like I'm describing it poorly.

I'm using Node.js at the moment, but I'm more curious if something like this exists.

So does anybody know of such a thing?

Thanks!

答:
What you're talking about is called mutation testing, and there are a number of implementations available.  I've not tried either, but there are at least two javascript versions:

grunt-mutation-testing, and

mutandis


问:
Does using == in JavaScript ever make sense?
In JavaScript, the Good Parts, Douglas Crockford wrote:

JavaScript has two sets of equality operators: === and !==, and their evil twins == and !=.  The good ones work the way you would expect.  If the two operands are of the same type and have the same value, then === produces true and !== produces false.  The evil twins do the right thing when the operands are of the same type, but if they are of different types, they attempt to coerce the values.  The rules by which they do that are complicated and unmemorable.  These are some of the interesting cases:

```<code>'' == '0'           // false
0 == ''             // true
0 == '0'            // true

false == 'false'    // false
false == '0'        // true

false == undefined  // false
false == null       // false
null == undefined   // true

' \t\r\n ' == 0     // true
</code>```

The lack of transitivity is alarming.  My advice is to never use the evil twins.  Instead, always use === and !==.  All of the comparisons just shown produce false with the === operator.

Given this unequivocal observation, is there ever a time when using == might actually be appropriate?

答:
I know this is a late answer, but there seems to be some possible confusion about null and undefined, which IMHO is what makes == evil, more so that the lack of transitivity, which is bad enough.  Consider:

```<code>p1.supervisor = 'Alice';
p2.supervisor = 'None';
p3.supervisor = null;
p4.supervisor = undefined;
</code>```

What do these mean?

p1 has a supervisor whose name is "Alice."

p2 has a supervisor whose name is "None."

p3 explicitly, unequivocally, does not have a supervisor.

p4 may or may have a supervisor. We don't know, we don't care, we're not supposed to know (privacy issue?), as in it's none of our business.

When you use == you are conflating null and undefined which is wholly improper. The two terms mean completely different things! Saying that I don't have a supervisor simply because I refused to tell you who my supervisor is is wrong!

I understand there are programmers who don't care about this difference between null and undefined or choose to use these terms differently. And if your world does not use null and undefined correctly, or you wish to give your own interpretation to these terms, so be it. I don't think that's a good idea though.

Now by the way I have no problem with null and undefined both being falsy! It is perfectly okay to say

```<code>if (p.supervisor) { ... }
</code>```

and then null and undefined would cause the code that processes the supervisor to be skipped. That is correct, because we don't know or don't have a supervisor. All good. But the two situations are not equal. This is why == is wrong. Again, things can be falsy and used in a duck typing sense, which is great for dynamic languages. It is proper JavaScript, Pythonic, Rubyish, etc. But again, these things are NOT equal.

And don't get me started on non-transitivity: "0x16" == 10, 10 == "10" but not "10" == "0x16". Yes, JavaScript is weakly types. Yes, it is coercive. But coerciveness should never, ever, apply to equality.

By the way, Crockford does have strong opinions. But you know what? He is correct here!

FWIW I understand that there are, and I have personally run into, situations where == is convenient! Like taking string input for numbers and, say, comparing to 0. However, this is hack. You have convenience as a tradeoff for an inaccurate model of the world.

TL;DR: falsiness is a great concept. It should not extend to equality.

Body:
I know this is a late answer, but there seems to be some possible confusion about null and undefined, which IMHO is what makes == evil, more so that the lack of transitivity, which is bad enough.  Consider:

p1.supervisor = 'Alice';
p2.supervisor = 'None';
p3.supervisor = null;
p4.supervisor = undefined;

What do these mean?

p1 has a supervisor whose name is "Alice."

p2 has a supervisor whose name is "None."

p3 explicitly, unequivocally, does not have a supervisor.

p4 may or may have a supervisor. We don't know, we don't care, we're not supposed to know (privacy issue?), as in it's none of our business.

When you use == you are conflating null and undefined which is wholly improper. The two terms mean completely different things! Saying that I don't have a supervisor simply because I refused to tell you who my supervisor is is wrong!

I understand there are programmers who don't care about this difference between null and undefined or choose to use these terms differently. And if your world does not use null and undefined correctly, or you wish to give your own interpretation to these terms, so be it. I don't think that's a good idea though.

Now by the way I have no problem with null and undefined both being falsy! It is perfectly okay to say

if (p.supervisor) { ... }

and then null and undefined would cause the code that processes the supervisor to be skipped. That is correct, because we don't know or don't have a supervisor. All good. But the two situations are not equal. This is why == is wrong. Again, things can be falsy and used in a duck typing sense, which is great for dynamic languages. It is proper JavaScript, Pythonic, Rubyish, etc. But again, these things are NOT equal.

And don't get me started on non-transitivity: "0x16" == 10, 10 == "10" but not "10" == "0x16". Yes, JavaScript is weakly types. Yes, it is coercive. But coerciveness should never, ever, apply to equality.

By the way, Crockford does have strong opinions. But you know what? He is correct here!

FWIW I understand that there are, and I have personally run into, situations where == is convenient! Like taking string input for numbers and, say, comparing to 0. However, this is hack. You have convenience as a tradeoff for an inaccurate model of the world.

TL;DR: falsiness is a great concept. It should not extend to equality.


问:
Tracking internal builds versus public builds
At our office, we use JIRA to track issues reported by our QA teams. We also have Bamboo which builds each time we commit to our Git (Stash) repository. QA picks a build from Bamboo and they work with that build for about a week. Once all of the issues they filed on that build are resolved, they pick another build and regress/smoke test again until they find a fully passing build (i.e. no issues reported).

The problem is they want to be able to track changelogs between the internal builds they choose (the build they pick from bamboo) and our public release version which has been planned.

So for example, if our "public release" version is 1.0, then our internal builds will be 1.0.1, 1.0.2, and so on. They might pick a build in Bamboo 50 builds later and mark that as the public release. So even though we marketed our product to be version 1.0, the actual version is 1.0.50 (50 being our internal build number).

They want to track changelogs between each internal round of testing and also track changelogs on the public release as a whole. So let's say they picked the following builds for their weekly rounds of testing:

```<code>1.0.1 -> 1.0.25 -> 1.0.50
</code>```

They want to see which JIRA issues are resolved between 1.0.1 and 1.0.25, and likewise between 1.0.25 and 1.0.50. The only solution I can think of for this problem is to add 4 versions to our project in JIRA:

```<code>1.0
1.0.1
1.0.25
1.0.50
</code>```

1.0 would be unreleased, and each time QA adds an internal build, it will be immediately marked as released. This will allow them to assign 2 affects or fix versions per issue: 1.0 and 1.0.25 (or whatever internal build it was reported on)

This seems clunky, I don't like the idea of adding versions in JIRA for internal builds. It seems like JIRA should only care about public releases (i.e. 1.0 in this case). Is there a better way to handle this type of continuous integration / continuous delivery?

答: Presumably, build 1.0.50 happened on a certain date, and any Jira tickets resolved before that date represent fixes or features contained in that build (if not, the "resolved" status is probably being misused). So it should be possible to accomplish this by making custom filters that list all tickets resolved between certain dates (and affecting v1.0). That way Jira doesn't have to know about build numbers, and the testers can simply use the "QA Week 2" filter.


答:
How can I avoid this kind of cascading refactor in the future?

Wishful Thinking Design

The goal is excellent OO design and implementation for the new feature. Avoiding refactoring is also a goal.

Start from scratch and make a design for the new feature that is what you wish you had. Take the time to do it well.

Note however that the key here is "add a feature". New stuff tends to let us largely ignore the current structure of the code base.  Our wishful thinking design is independent. But we then need two more things:

Refactor only enough to make a necessary seam to inject/implement the new feature's code.

Resistance to refactoring should not drive the new design.

Write a client facing class with an API that keeps the new feature & existing codez blissfully ignorant of each other.

It transliterates to get objects, data, and results back and forth. Least knowledge principle be damned. We're not going to do anything worse than what existing code already does.

Heuristics, Lessons Learned, etc.

Refactoring has been as simple as adding an default parameter to an existing method call; or a single call to a static class method.

Extension methods on existing classes can help keep the new design's quality with absolute minimal risk.

"Structure" is everything. Structure is the realization of the Single Responsibility Principle; design that facilitates functionality. Code will stay short and simple all the way up the class hierarchy. Time for new design is made up during testing, re-work, and avoiding hacking through the legacy code jungle.

Wishful thinking classes focus on the task at hand. Generally, forget about extending an existing class - you're just inducing the refactor cascade again & having to deal with the "heavier" class' overhead.

Purge any remnants of this new functionality from existing code. Here, complete and well encapsulated new feature functionality is more important than avoiding refactoring.

Title: How do I avoid cascading refactorings?