问:
Storing and retrieving simple data within a framework
I'm determined to get a decent answer to this, because while I have my own approach (constants) I'm not convinced I'm doing it as efficiently as I could be.

So I'm editing the entire question, to add actual code for a more clear description, and am adding a bounty (as much as I can).

(Sorry Ixrec, your answer might not stand any more).

Basic overview of my (simple) framework

htaccess sends all requests to Front Controller (index.php)

Front Controller loads Bootstrap.php

Bootstrap loads all other framework things - e.g. Error reporting
setup; Auto loading; PHP Version check; Router;

Problem

I'm stuck at deciding on the best way to store "simple data" that's used throughout the framework. Some used 3-4 times, some only once (at the moment).

Simple data is things like: PHP Version Running; Minimum PHP Version framework requires to operate; Allowed characters in the URI; Framework data (name, support contact details);

While arrays and constants are simple and affective, they instantly pollute the global space, and constants do so indefinitely (end of stack).

Classes seems good approach in terms of data is only called where needed, and so global space is not just immediately polluted with all data.

However, a class to just store some small data seems over kill (i.e. "5.4.0").

So I am conflicted with what option to choose, as all have pros and cons.

I can choose, but wanted some feedback from more seasoned devs.

Requirements

1)

Data to be re-usable.

Not all, but most data will likely be used in multiple classes/files/templates (or at least want it open for future possibilities).

2)

Avoid over polluting global data as much as possible (i.e. just including a file with 50 data items in an array or 50 constants).

While the data needs to be re-usable, and so global (i.e. constants) is the easiest option, I am trying to avoid just shoving it all into global instantly.

I also feel it's best to keep all this data as one type, ie ALL in an array, or ALL in constants, and all in one place - making it easy to manage.

But if that is not the best approach do say - remember while it is different data for different components, so arguably some could be in classes, some array, some constants etc, they have a common ground in that they are ALL simple data. So whatever option is best it will be likely be best for all this data.

Examples/Options

I have a "PHP Version Check", which is a class loaded early on in Bootstrap which checks if the running (server) PHP version is adequate for what the framework requires to operate.

So using the data required for that component as an example of the data problem I face:

NOTE: There are currently about 50 data items. The examples below only have one data item, which makes it appear as if the issues don't matter, especially polluting global space (the total data items will likely also grow in the future).

OPTION 1 - ARRAY

```<code>$ConfigArray['phpVersionRunning'] = PHP_VERSION;
$ConfigArray['phpVersionRequired'] = '5.4.0';
</code>```

PROS

Data will be in a single array, a simple approach.

CONS

Data is immediately pushed into global.

Data can be altered.

Array name and array index name being long enough to be descriptive means long code in other files where this data is needed.

e.g. if ( $ConfigArray['phpVersionRequired'] !==  $ConfigArray['phpVersionRunning'] )

OPTION 2 - CONSTANTS

```<code>define ('PHP_VERSION_RUNNING', PHP_VERSION);
define ('PHP_VERSION_REQUIRED', '5.4.0');
</code>```

PROS

This is the most simple and clean looking approach, where used in other files constants are clear in their purpose etc.

e.g. if ( PHP_VERSION_RUNNING !==  PHP_VERSION_REQUIRED )

Instantly accessible wherever needed, including in classes.

Data cannot be altered.

CONS

They are all pushed into global instantly.

They remain in global right through Front End, controllers, templates, view, etc, and won't be needed by them.

OPTION 3 - CLASS

```<code>class PhpVersionData
  {

    private $VersionRunning;
    private $VersionRequired;

    protected function __construct()
      {
        $this->VersionRunning = PHP_VERSION;
        $this->VersionRequired = '5.4.0';
      }

    protected function getVersionRunning()
      {
        return $this->VersionRunning;
      }

    protected function getVersionRequired()
      {
        return $this->VersionRequired;
      }

  }
</code>```

PROS

Data is only created at the first point where it's needed.

CONS

Firstly, this just looks way OTT for just basic data.

Constructor and Methods can be protected, so class would need extending so not instantly polluting global space, but then am treading into singleton territory and also tight coupling (?).

If public methods/constructor instead, then am back to potential global pollution issue.

OPTION 4 - Separate data loading:

Another approach is to use constants, or array or variables, but stored in separate files. So each file could be included separately and only when needed.

This avoids everything being immediately in global space, and with array/constant I could unset them once they are no longer needed.

On paper, this sounds like a great idea, but in practice it seems very fiddly, and maintaining it would be harder as data is stored and called all over the place.

Summary

They all have pros and cons which conflict each other. While one option seems ideal, such as constants, it has a major con which pollutes global space indefinitely.

In honesty, I'm swayed to a config array, as although it is pushed into global from the start, I can clean it up at points in the stack where it's no longer needed.

But there are pros and cons to all approaches, and would like to know what is the most robust approach juggling global space pollution, maintainability, ease of use/readability, etc.

答:
If you have enough of these little configuration values that you feel the need to put them in another file, then they should go in a configuration file, not a source code file. There are countless ways of implementing config files, but I believe PHP has some standard approaches.

To answer your numbered questions more directly:

1) They're never really "necessary", but they're definitely useful once you have a lot of data. But again, they should be actual data files, not just code files that contain object literals.

2) A class whose sole purpose is to provide access to these values is not so good. But a class whose sole purpose is to parse config files is perfectly fine (and you'll typically get this from a library).

3) I believe the link I gave above is a good place to start.


问:
Constructor-only subclasses: Is this an anti-pattern?
I was having a discussion with a co-worker, and we ended up having conflicting intuitions about the purpose of subclassing. My intuition is that if a primary function of a subclass is to express a limited range of possible values of its parent, then it probably shouldn't be a subclass. He argued for the opposite intuition: that subclassing represents an object's being more "specific", and therefore a subclass relationship is more appropriate.

To put my intuition more concretely, I think that if I have a subclass that extends a parent class but the only code that subclass overrides is a constructor (yes, I know constructors don't generally "override", bear with me), then what was really needed was a helper method.

For example, consider this somewhat real-life class:

public class DataHelperBuilder
{
    public string DatabaseEngine { get; set; }
    public string ConnectionString { get; set; }

    public DataHelperBuilder(string databaseEngine, string connectionString)
    {
        DatabaseEngine = databaseEngine;
        ConnectionString = connectionString;
    }

    // Other optional "DataHelper" configuration settings omitted

    public DataHelper CreateDataHelper()
    {
        Type dataHelperType = DatabaseEngineTypeHelper.GetType(DatabaseEngine);
        DataHelper dh = (DataHelper)Activator.CreateInstance(dataHelperType);
        dh.SetConnectionString(ConnectionString);

        // Omitted some code that applies decorators to the returned object
        // based on omitted configuration settings

        return dh;
    }
}
```

<p>His claim is that it would be entirely appropriate to have a subclass like this:</p>

<pre class="lang-cs prettyprint-override"><code>public class SystemDataHelperBuilder
{
    public SystemDataHelperBuilder()
        : base(Configuration.GetSystemDatabaseEngine(),
               Configuration.GetSystemConnectionString())
    {
    }
 }
</code>```

So, the question:

Among people who talk about design patterns, which of these intuitions is correct? Is subclassing as described above an anti-pattern?

If it is an anti-pattern, what is its name?

I apologize if this turns out to have been an easily googleable answer; my searches on google mostly returned information about the telescoping constructor anti-pattern and not really what I was looking for.

答:
I use constructor only subclasses quite regularly to express different concepts.

For example, consider the following class:

```<code>public class Outputter
{
    private readonly IOutputMethod outputMethod;
    private readonly IDataMassager dataMassager;

    public Outputter(IOutputMethod outputMethod, IDataMassager dataMassager)
    {
        this.outputMethod = outputMethod;
        this.dataMassager = dataMassager;
    }

    public MassageDataAndOutput(string data)
    {
        this.outputMethod.Output(this.dataMassager.Massage(data));
    }
}
</code>```

We can then create a subclass:

```<code>public class CapitalizeAndPrintOutputter : Outputter
{
    public CapitalizeAndPrintOutputter()
        : base(new PrintOutputMethod(), new Capitalizer())
    {
    }
}
</code>```

You can then use a CapitalizeAndPrintOutputter anywhere in your code and you know exactly what type of outputter it is.  Furthermore, this pattern actually makes it very easy to use a DI container to create this class.  If the DI container knows about PrintOutputMethod and Capitalizer it can even automatically create the CapitalizeAndPrintOutputter for you.

Using this pattern is really quite flexible and useful.  Yes, you can use factory methods to do the same thing, but then (at least in C#) you lose some of the power of the type system and certainly using DI containers becomes more cumbersome.

ContentLicense: CC BY-SA 3.0

Body:
I use constructor only subclasses quite regularly to express different concepts.

For example, consider the following class:

public class Outputter
{
    private readonly IOutputMethod outputMethod;
    private readonly IDataMassager dataMassager;

    public Outputter(IOutputMethod outputMethod, IDataMassager dataMassager)
    {
        this.outputMethod = outputMethod;
        this.dataMassager = dataMassager;
    }

    public MassageDataAndOutput(string data)
    {
        this.outputMethod.Output(this.dataMassager.Massage(data));
    }
}

We can then create a subclass:

public class CapitalizeAndPrintOutputter : Outputter
{
    public CapitalizeAndPrintOutputter()
        : base(new PrintOutputMethod(), new Capitalizer())
    {
    }
}

You can then use a CapitalizeAndPrintOutputter anywhere in your code and you know exactly what type of outputter it is.  Furthermore, this pattern actually makes it very easy to use a DI container to create this class.  If the DI container knows about PrintOutputMethod and Capitalizer it can even automatically create the CapitalizeAndPrintOutputter for you.

Using this pattern is really quite flexible and useful.  Yes, you can use factory methods to do the same thing, but then (at least in C#) you lose some of the power of the type system and certainly using DI containers becomes more cumbersome.


问:
SQL - Algorithm for finding availability of a resource
I'm having trouble creating a mysql compatible algorithm for this.

Background

App with mysql, perl and JS. It's a booking system where each booking is comprised of a start, end and qty.  Start and end are timestamps.

Schema simplified to a single table:

|  bookings
|-------------------
| id    | pkey
| start | timestamp
| end   | timestamp
| qty   | int
```

<h2>Question</h2>

<p>In SQL, how do you check how many resources are booked at once for a given <code>timeRange</code>? Code with explanation or an algorithm that is SQL compatible both work.</p>

<p>So, for the following schedule:</p>

<pre class="lang-none prettyprint-override"><code>09:00 -----               <-|
09:30 |   |                 | A maximum of 12 are booked at once during this range
10:00 |x7 |                 |
10:30 ----- ----- -----     |
11:00       |   | |   |     |
11:30       |x2 | |x10|   <-|
12:00       |   | |   |
12:30       ----- -----
</code>```

I should get 12 since the x2 and x10 bookings don't overlap with the x7 booking, so there are never more than 12 items booked at once between 9:00 and 11:30.

Progress

--It's been heavily shrunk to show just the relevant part, so it might have some errors
SELECT coalesce(max(qtyOverlap.sum),0) booked
FROM (
    SELECT coalesce(sum(b2.qty),0) sum
        FROM booking b1
        LEFT JOIN (
            SELECT b.qty, b.tStart, b.tEnd FROM booking b
        ) b2
        ON b1.tStart < b2.tEnd AND
           b1.tEnd > b2.tStart AND
           b2.tStart < '2015-02-19 16:30:00' AND
           b2.tEnd > '2015-02-19 06:00:00'
        WHERE
              b1.tStart < '2015-02-19 16:30:00' AND
              b1.tEnd > '2015-02-19 06:00:00'
        GROUP BY b1.id
) qtyOverlap
GROUP BY qtyOverlap.itemId
```

<p>Which is this algorithm:</p>

<pre class="lang-none prettyprint-override"><code>Max of
    For each booking that overlaps given timeRange
        return sum of
            each booking that overlaps this booking and given timeRange
</code>```

In the schedule above this would be:

```<code>max([7],[2+10],[10+2]) = 12
</code>```

But given a schedule like:

09:00 -----               <-|
09:30 |   |                 | A maximum of 17 are booked at once during this range, not 19
10:00 |x7 |                 |
10:30 |   |       -----     |
11:00 -----       |   |     |
11:30       ----- |x10|   <-|
12:00       |x2 | |   |
12:30       ----- -----
```

<p>This gives:</p>

```max([7+10],[2+10],[10+7+2]) = 19
```

<p>Which is wrong.</p>

<p>The only way I can think of to fix this is to use recursion (which isn't mysql compatible afaik).</p>

<p>It would look something like (in working JS code)</p>

```function getOverlaps(bookings,range) {
    return bookings.filter(function(booking){
        return isOverLapping(booking,range);
    });
}
function isOverLapping(a, b) {
    return (a.start  b.start);
}
function maxSum(booking, overlaps) { // main recursive function
    var currentMax = 0;
    var filteredOverlaps = getOverlaps(overlaps,booking);
    for (var i = 0; i < filteredOverlaps.length; i++) {
        currentMax = Math.max(
            maxSum(filteredOverlaps[i], removeElement(filteredOverlaps,i)),
            currentMax
        );
    }
    return currentMax + booking.qty;
}
function removeElement(array,i){
    var clone = array.slice(0)
    clone.splice(i,1);
    return clone;
}
var maxBooked = maxSum(timeRange, getOverlaps(bookings,timeRange));
```

Visual JSFiddle demo

Any way to do this in SQL? (any reasonable way, that is)

Update
I just tried to use a stored procedure recursion emulation method as documented here. But part way through implementing it, I tried it with the demo data and decided the performance was far too terrible. Actually, it just needed indexing. Now it's just 'kinda' bad.

答:
This is a possibility with SQL, however it needs to generate a sequence of numbers, since SQL server i was testing this does not support it I had to fetch the sequence from sys.all_objects ROW_NUMBER() function,

```<code>SELECT n = ROW_NUMBER() OVER (ORDER BY [object_id])
FROM sys.all_objects
</code>```

the approach is to generate a view with number of time intervals small enough for your booking systems smallest allowed time slot (in this case I used 5 minutes and you can change it as you want)

```<code>select
DATEADD(MINUTE, 5 * n, '2015-02-19 08:00:00') t_start,
DATEADD(MINUTE, 5 * (n + 1), '2015-02-19 08:00:00') t_end
from
bookings b,
(
  SELECT n = ROW_NUMBER() OVER (ORDER BY [object_id])
  FROM sys.all_objects
) numbers
where
DATEADD(MINUTE, 5 * (n + 1), '2015-02-19 08:00:00') < '2015-02-19 17:00:00'
</code>```

So the date value passed to the DATEADD function would be the from time and the one used in the last is the end time. This will generate resultset like this,

```<code>t_start                 |  t_end
--------------------------------------------------
2015-02-19 08:05:00.000 |  2015-02-19 08:10:00.000
2015-02-19 08:10:00.000 |  2015-02-19 08:15:00.000
2015-02-19 08:15:00.000 |  2015-02-19 08:20:00.000
.................
</code>```

Going a bit out of question and you can see sum for each period from this query

```<code>select
tInt.t_start,
tInt.t_end,
(select sum(b.qty) from bookings b where b.tstart <= tInt.t_start and b.tend >= tInt.t_end) as total
from
(
select
DATEADD(MINUTE, 5 * n, '2015-02-19 08:00:00') t_start,
DATEADD(MINUTE, 5 * (n + 1), '2015-02-19 08:00:00') t_end
from
bookings b,
(
  SELECT n = ROW_NUMBER() OVER (ORDER BY [object_id])
  FROM sys.all_objects
) numbers
where
DATEADD(MINUTE, 5 * (n + 1), '2015-02-19 08:00:00') < '2015-02-19 17:00:00'
)
tInt
</code>```

will result in,

```<code>t_start                | t_end                      |total
-----------------------------------------------------------
2015-02-19 08:55:00.000|    2015-02-19 09:00:00.000 |NULL
same repeating.....    |                            |
2015-02-19 09:00:00.000|    2015-02-19 09:05:00.000 |7
same repeating.....    |                            |
2015-02-19 10:30:00.000|    2015-02-19 10:35:00.000 |NULL
same repeating.....    |                            |
2015-02-19 11:00:00.000|    2015-02-19 11:05:00.000 |10
same repeating.....    |                            |
2015-02-19 12:00:00.000|    2015-02-19 12:05:00.000 |12
same repeating.....    |                            |
2015-02-19 12:30:00.000|    2015-02-19 12:35:00.000 |NULL
same repeating.....
</code>```

Now all you have to do is to get max value

Body:
This is a possibility with SQL, however it needs to generate a sequence of numbers, since SQL server i was testing this does not support it I had to fetch the sequence from sys.all_objects ROW_NUMBER() function,

SELECT n = ROW_NUMBER() OVER (ORDER BY [object_id])
FROM sys.all_objects

the approach is to generate a view with number of time intervals small enough for your booking systems smallest allowed time slot (in this case I used 5 minutes and you can change it as you want)

select
DATEADD(MINUTE, 5 * n, '2015-02-19 08:00:00') t_start,
DATEADD(MINUTE, 5 * (n + 1), '2015-02-19 08:00:00') t_end
from
bookings b,
(
  SELECT n = ROW_NUMBER() OVER (ORDER BY [object_id])
  FROM sys.all_objects
) numbers
where
DATEADD(MINUTE, 5 * (n + 1), '2015-02-19 08:00:00') < '2015-02-19 17:00:00'

So the date value passed to the DATEADD function would be the from time and the one used in the last is the end time. This will generate resultset like this,

t_start                 |  t_end
--------------------------------------------------
2015-02-19 08:05:00.000 |  2015-02-19 08:10:00.000
2015-02-19 08:10:00.000 |  2015-02-19 08:15:00.000
2015-02-19 08:15:00.000 |  2015-02-19 08:20:00.000
.................

Going a bit out of question and you can see sum for each period from this query

select
tInt.t_start,
tInt.t_end,
(select sum(b.qty) from bookings b where b.tstart <= tInt.t_start and b.tend >= tInt.t_end) as total
from
(
select
DATEADD(MINUTE, 5 * n, '2015-02-19 08:00:00') t_start,
DATEADD(MINUTE, 5 * (n + 1), '2015-02-19 08:00:00') t_end
from
bookings b,
(
  SELECT n = ROW_NUMBER() OVER (ORDER BY [object_id])
  FROM sys.all_objects
) numbers
where
DATEADD(MINUTE, 5 * (n + 1), '2015-02-19 08:00:00') < '2015-02-19 17:00:00'
)
tInt

will result in,

t_start                | t_end                      |total
-----------------------------------------------------------
2015-02-19 08:55:00.000|    2015-02-19 09:00:00.000 |NULL
same repeating.....    |                            |
2015-02-19 09:00:00.000|    2015-02-19 09:05:00.000 |7
same repeating.....    |                            |
2015-02-19 10:30:00.000|    2015-02-19 10:35:00.000 |NULL
same repeating.....    |                            |
2015-02-19 11:00:00.000|    2015-02-19 11:05:00.000 |10
same repeating.....    |                            |
2015-02-19 12:00:00.000|    2015-02-19 12:05:00.000 |12
same repeating.....    |                            |
2015-02-19 12:30:00.000|    2015-02-19 12:35:00.000 |NULL
same repeating.....

Now all you have to do is to get max value


答:
Let me first note that as the code is written, the sub-class is not actually more specific that the parent, as the two fields initialized are both settable by client code.

An instance of the subclass can only be distinguished using a downcast.

Now, if you have a design in which the DatabaseEngine and ConnectionString properties were reimplemented by the subclass, which accessed Configuration to do so, then you have a constraint which makes more sense of having the subclass.

Having said that, "anti-pattern" is too strong for my taste; there is nothing really wrong here.

Title: Constructor-only subclasses: Is this an anti-pattern?

Body:
I was having a discussion with a co-worker, and we ended up having conflicting intuitions about the purpose of subclassing. My intuition is that if a primary function of a subclass is to express a limited range of possible values of its parent, then it probably shouldn't be a subclass. He argued for the opposite intuition: that subclassing represents an object's being more "specific", and therefore a subclass relationship is more appropriate.

To put my intuition more concretely, I think that if I have a subclass that extends a parent class but the only code that subclass overrides is a constructor (yes, I know constructors don't generally "override", bear with me), then what was really needed was a helper method.

For example, consider this somewhat real-life class:

public class DataHelperBuilder
{
    public string DatabaseEngine { get; set; }
    public string ConnectionString { get; set; }

    public DataHelperBuilder(string databaseEngine, string connectionString)
    {
        DatabaseEngine = databaseEngine;
        ConnectionString = connectionString;
    }

    // Other optional "DataHelper" configuration settings omitted

    public DataHelper CreateDataHelper()
    {
        Type dataHelperType = DatabaseEngineTypeHelper.GetType(DatabaseEngine);
        DataHelper dh = (DataHelper)Activator.CreateInstance(dataHelperType);
        dh.SetConnectionString(ConnectionString);

        // Omitted some code that applies decorators to the returned object
        // based on omitted configuration settings

        return dh;
    }
}
```

<p>His claim is that it would be entirely appropriate to have a subclass like this:</p>

<pre class="lang-cs prettyprint-override"><code>public class SystemDataHelperBuilder
{
    public SystemDataHelperBuilder()
        : base(Configuration.GetSystemDatabaseEngine(),
               Configuration.GetSystemConnectionString())
    {
    }
 }
</code>```

So, the question:

Among people who talk about design patterns, which of these intuitions is correct? Is subclassing as described above an anti-pattern?

If it is an anti-pattern, what is its name?

I apologize if this turns out to have been an easily googleable answer; my searches on google mostly returned information about the telescoping constructor anti-pattern and not really what I was looking for.


问:
Anything wrong with direct evaluation of JSON if your own code created it?
Suppose I have a server-side variable containing JSON (named strJSON) that my own code created.  In JavaScript I can consume it like this:

```<code>var data = <%= strJSON %>;
</code>```

or use a JSON parsing library:

```<code>var data = JSON.parse('<%= HttpUtility.JavaScriptStringEncode(strJSON) %>');
</code>```

I prefer the 2nd, for safety. Is what I'm doing unnecessary?

答:
No, there is nothing wrong with evaluating your own code, if you know for certain it's safe. Too many get caught up in blindly following rules. Evaluation of code in a string seems to really bring out strong opinions for some reason.

Evaluation of code in a string is a tool. Learn what it does, how it works, and why it can be unsafe. When you really understand why you generally shouldn't use evaluation, you then become free to use it when it's the right tool for the job.

If you think it's probably safe, don't do it. When you know it's safe, there's no reason not to do it.


问:
Semantics of heading levels in multiple sections in HTML5
I'm never quite sure what is the best, most semantic way to handle heading levels in HTML5 markup, when you have multiple sections. On one hand it makes sense to have an H1 heading as a title of a section, or an article, but it leads to these weird situations when your whole document outline is made out of H1 headings.

```<code><header>
    <h1>Site heading</h1>
</header>
...
<section>
    <h1>Section heading</h1>
    <article>
        <h1>Article heading</h1>
        ...
    </article>
    ...
    <section>
        <h1>Subsection heading</h1>
        <article>
            <h1>Subsection article heading</h1>
            ...
        </article>
        ...
    </section>
</section>
</code>```

Is this really the way to do it in HTML5? It feels a bit like the heading tags don't carry no semantic value anymore. When you see an H1 tag in a markup it doesn't tell you anything about the headings position in the document's outline.

On the other hand, when you mark your headings hierarchically, like you would before the HTML5's markup, it creates a situations where one article has a different heading level than another, while having the same level as a subsection, which also doesn't make much sense.

```<code><header>
    <h1>Site heading</h1>
</header>
...
<section>
    <h2>Section heading</h2>
    <article>
        <h3>Article heading</h3>
        ...
    </article>
    ...
    <section>
        <h3>Subsection heading</h3>
        <article>
            <h4>Subsection article heading</h4>
            ...
        </article>
        ...
    </section>
</section>
</code>```

From what I read, I understand that the first way is the correct way in HTML5, but it just doesn't feel right. Having often a whole site without single third level heading feels weird, but it might be just a case of old habits dying hard on my part, maybe?

答:
While the first way is "correct", a lot of screen readers will not interpret it as such, so the second way is more useful from an accessibility point of view.

If you are worried about the semantics, you can use the more generic HTML5  element, which:

represents a group of introductory or navigational aids. It may contain some heading elements but also other elements like a logo, wrapped section's header, a search form, and so on.

For example:

```<code><header>
    <header>Site heading</header>
</header>
...
<section>
    <header>Section heading</header>
    <article>
        <header>Article heading</header>
        ...
    </article>
    ...
    <section>
        <header>Subsection heading</header>
        <article>
            <header>Subsection article heading</header>
            ...
        </article>
        ...
    </section>
</section>
</code>```

Essentially, it carries much the same semantics as your first example, however the nested use of sections provides a semantic hierarchy to the  elements, that isn't immediately understandable by the use of nested
.

Your concern then becomes about styling, which is a presentation issue and can be done in CSS:

```<code>header {
    font-weight: blod;
}
section > header {
    font-size:140%; /* like h1 */
}

section > section > header
    font-size:130%; /* like h2 */
}

section > section > header
    font-size:120%; /* like h3 */
}
</code>```

Body:
While the first way is "correct", a lot of screen readers will not interpret it as such, so the second way is more useful from an accessibility point of view.

If you are worried about the semantics, you can use the more generic HTML5 <header> element, which:

represents a group of introductory or navigational aids. It may contain some heading elements but also other elements like a logo, wrapped section's header, a search form, and so on.

For example:

<header>
    <header>Site heading</header>
</header>
...
<section>
    <header>Section heading</header>
    <article>
        <header>Article heading</header>
        ...
    </article>
    ...
    <section>
        <header>Subsection heading</header>
        <article>
            <header>Subsection article heading</header>
            ...
        </article>
        ...
    </section>
</section>

Essentially, it carries much the same semantics as your first example, however the nested use of sections provides a semantic hierarchy to the <header> elements, that isn't immediately understandable by the use of nested <h1>.

Your concern then becomes about styling, which is a presentation issue and can be done in CSS:

header {
    font-weight: blod;
}
section > header {
    font-size:140%; /* like h1 */
}

section > section > header
    font-size:130%; /* like h2 */
}

section > section > header
    font-size:120%; /* like h3 */
}


问:
The recommended Way to exit a Loop
Occasionally - but recurringly - I face the following loop pattern problem:

```<code>CodeSnippet1
DO WHILE LoopCondition   //LoopCondition depends on some pre-calculation from CodeSnippet1
    CodeSnippet2         //CodeSnippet2 relies on LoopConditon=true
    CodeSnippet1
LOOP
</code>```

The problem I see here is the code duplication of CodeSnippet1.

At the first glance, it seems like I should move the condition to the end:

```<code>DO
    CodeSnippet1
    CodeSnippet2
LOOP WHILE LoopCondition
</code>```

This won't work since CodeSnippet2 assumes LoopCondition=true. The next try would be:

```<code>DO
    CodeSnippet1
    IF LoopCondition THEN CodeSnippet2
LOOP WHILE LoopCondition
</code>```

Again far from elegant.

In C-like programming languages, one can do the following:

```<code>while(complicated-expression-containing-CodeSnippet1-and-LoopCondition) {
    CodeSnippet2
}
</code>```

But

a) this can get difficult to understand and

b) not every programming language can perform arbitrary calculations, especially variable assigments, during evaluation of some loop condition.

Recently, I came up with the following way:

```<code>DO //endless loop
    CodeSnippet1

    IF NOT LoopCondition THEN EXIT LOOP

    CodeSnippet2
LOOP
</code>```

This tends to lead structured programming with loops ad absurdum / reminds me a bit of GoTo programming style.

My Question:

Are there (more or less) objective reasons to prefer one of the mentioned loop programming styles over the others?

EDIT:

I know in many occasions CodeSnippet1 together with LoopCondition can be encapsulated in a function returning the loop condition, and we're done. I agree with that. But this does not hold in general. Above in b) I tried to hint at "variable assignments". Here in detail:

My favourite minimal but real-world example: Using a BufferedReader in Java:

```<code>line = bufferedReader.readLine();
while(line != null) {
    //CodeSnippet2
    line = bufferedReader.readLine();
}
</code>```

vs.

```<code>while((line = bufferedReader.readLine()) != null) {
    //CodeSnippet2
}
</code>```

Both variants are not satisfying. Factoring out (line = bufferedReader.readLine()) != null into a function that returns a boolean has one new problem: How to retrieve line? Using a global variable / class member just for this purpose?

答:
I was told in school that escaping a loop using GOTO or equivalent (such as "break" in C) is a bad style of programming. A school-approved way is to introduce a variable as a switch that once active will cause a loop to exit.

In C, this is a school-approved way to write a loop:

```<code>int bool=0;
int count=0;
while (count < 100 && bool==0){
    count++;
    if (count == 10){
        bool=1;
    }
}
</code>```

This is not a school-approved way to write a loop:

```<code>int count=0;
while (count < 100){
    count++;
    if (count == 10){
        break;
    }
}
</code>```

However, the non-school approved way uses a few bytes less of stack space (because one less integer is reserved for the program).

Title: The recommended Way to exit a Loop

Body:
I was told in school that escaping a loop using GOTO or equivalent (such as "break" in C) is a bad style of programming. A school-approved way is to introduce a variable as a switch that once active will cause a loop to exit.

In C, this is a school-approved way to write a loop:

int bool=0;
int count=0;
while (count < 100 && bool==0){
    count++;
    if (count == 10){
        bool=1;
    }
}

This is not a school-approved way to write a loop:

int count=0;
while (count < 100){
    count++;
    if (count == 10){
        break;
    }
}

However, the non-school approved way uses a few bytes less of stack space (because one less integer is reserved for the program).


问:
How to use unit tests when using BDD?
I am trying to understand BDD. I've read some articles and as I understood BDD is "the next step" from TDD.
I say that because I find both to be very similar, and as I could read in this article, BDD was born as an improvement from TDD.
Great, I really like the idea.

There is one practical point that I do not get, though: there is a .feature file in which the BA will write all the expected behavior in the system. As a BA, he has no idea how the system is built, so we will write something like this:

+Scenario 1: Account is in credit+

Given the account is in credit

And the card is valid

And the dispenser contains cash

When the customer requests cash

Then ensure the account is debited And ensure cash is dispensed

And ensure the card is returned

Ok, this is great, but there are many parts of the system that will collaborate so that it can happen (think of Account obj, Dispenser obj, Customer obj and so on). To me this looks like an integration test.

I would like to have Unit Tests.  How do I test the code that checks if the dispenser has money? Or that the cash is dispensed? Or that the account is debited when required?
How can I mix unit tests with "BA Created" tests?

答:
I am trying to understand BDD. I've read some articles and as I understood BDD is "the next step" from TDD. I say that because I find both to be very similar, and as I could read in this article, BDD was born as an improvement from TDD.

Actually, no, BDD is not "the next step" from TDD. It is TDD. Or more precisely, it is a rephrasing of TDD.

The creators of BDD noticed that the major hurdle to understanding that TDD is not about testing but about behavioral specification was that all the TDD terminology is about testing and not about behavioral specification. It's like trying not to think of a pink elephant when someone says to you "try not to think of a pink elephant", except with the added complication of being in a room full of pink elephants and a guy constantly yelling "pink elephant, pink elephant, pink elephant" in your ear.

So, they rephrased TDD in terms of behavioral specification. "Tests" and "test cases" are now "examples", "units" are "behaviors", "assertions" are "expectations", and so on.

However, the methodology is still the same. You start with an acceptance test (I mean "feature"), zoom in to a unit test (I mean "example"), zoom back out etc.

I would like to have Unit Tests.  How do I test the code that checks if the dispenser has money? Or that the cash is dispensed? Or that the account is debited when required?
  How can I mix unit tests with "BA Created" tests?

The same way you do in TDD. You can write your features and your examples in different frameworks (e.g. Cucumber and RSpec) or even different languages (e.g. writing examples for a C project in C, and features in FIT/Fitnesse), you can use a single features framework for both (e.g. writing examples and features in Cucumber) or you can use single examples framework for both (e.g. writing both in RSpec). You don't even have to use a framework at all.

An example of TDD-done-right (which is identical to BDD) using just a single framework is JUnit itself, which contains a mixture of unit tests (examples) and functional / integration tests (features), all written in JUnit itself.

I believe Kent Beck calls this "zooming". Start high-level, then "zoom in" to the details, then back out again.

ContentLicense: CC BY-SA 4.0

Title: How to use unit tests when using BDD?


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

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

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

答: You should know what it is and what the computer is doing.  Learning something like Knuth's MIX will help you.  Mostly being able to judge the efficiency of your code.  Go get the Art of Computer Programming and read it.  It will make you a smarter programmer.</p>

ContentLicense: CC BY-SA 2.5


问:
Need to store Multiple Images (path) into MySQL after upload
I am trying to build my own little eCommerce CMS, and i want the expert opinion on how to handle multiple uploaded files (images).

For Example:

A user adds a new item, fills the necessary form data and selects (nth) number of images and submits. I want to know how should i handle those images data into MySQL.

one thought i have in mind is that i create a separate table item_images Where i assign an ID or something like Item Code which inputs by the user and that Item Code will be the Identification for all the images?

PS: I dont want to upload Images directly to the Database, Just the paths/links.

Please advice.

答:
You could do this by creating 2 additional tables:

Table Images ( ImageID int, ImagePath varchar )

Table ImagesXUsers ( UserID int, ImageID int ) (or ImagesXPages or whatever it is you need to associate these images with)

Whenever images are uploaded, they are inserted into the Images table, and are appropriately associated with the user account via the ImagesXUsers table.

An example query for retrieving all the images for a given user account could be the following:

```<code>SELECT i.ImageID, i.ImagePath
FROM Images i
JOIN ImagesXUsers u ON
    u.ImageID = i.ImageID AND
    u.UserID = {whatever user is logged in}
</code>```

Body:
You could do this by creating 2 additional tables:

Table Images ( ImageID int, ImagePath varchar )

Table ImagesXUsers ( UserID int, ImageID int ) (or ImagesXPages or whatever it is you need to associate these images with)

Whenever images are uploaded, they are inserted into the Images table, and are appropriately associated with the user account via the ImagesXUsers table.

An example query for retrieving all the images for a given user account could be the following:

SELECT i.ImageID, i.ImagePath
FROM Images i
JOIN ImagesXUsers u ON
    u.ImageID = i.ImageID AND
    u.UserID = {whatever user is logged in}


问:
2 methods that are 75% the same?
I have code that violates the DRY principle and I would like to consolidate 2 methods as much as I can, but the problem I am facing is that they have some differences, I would say they are about 75% the same, but the other 25% is different in certain areas.  What kinds of design patterns or design approaches can I do to turn 2 methods into 1 or at least limit the code needed in each, so that they become more scalable and maintainable?

答:
This is difficult to answer without looking at the code.  However, it is clear that these methods are trying to do too much.  They are almost certainly violating the SRP.

I would suggest that you begin by looking at where the methods are different and why.  Perhaps you could use method injection to inject different code into the method, based on who or what is calling it.

Fundamentally, when it comes to refactoring code like this you should be trying to figure out why the code is the same and why it is different.  Once you understand these two things, you can then factor these methods so that they are no longer trying to do too much.

Title: 2 methods that are 75% the same?


答:
Too difficult to assess without having a code segment to analyse.

Method consolidation should definitely be applied here, you're just going to need to keep a few principles in mind. Have a read through this article on Jeff Atwood's blog:

Curly's Law: Do One Thing

Pay attention to the three core principles of modern software development, namely:

Don't Repeat Yourself

Once and Only Once, and

Single Point of Truth

Although I personally wouldn't recommend the following, I'm going to show you an example for simplicity sake if you simply wish to wrap things up:

```<code>function my_method(variable){
/*
 * 75% of method here
 */
if (variable == 0){
    /* variation one here */
}
else{
    /* variation two here */
}
return value;
}
</code>```

Title: 2 methods that are 75% the same?

Body: I have code that violates the DRY principle and I would like to consolidate 2 methods as much as I can, but the problem I am facing is that they have some differences, I would say they are about 75% the same, but the other 25% is different in certain areas.  What kinds of design patterns or design approaches can I do to turn 2 methods into 1 or at least limit the code needed in each, so that they become more scalable and maintainable?

Body:
Too difficult to assess without having a code segment to analyse.

Method consolidation should definitely be applied here, you're just going to need to keep a few principles in mind. Have a read through this article on Jeff Atwood's blog:

Curly's Law: Do One Thing

Pay attention to the three core principles of modern software development, namely:

Don't Repeat Yourself

Once and Only Once, and

Single Point of Truth

Although I personally wouldn't recommend the following, I'm going to show you an example for simplicity sake if you simply wish to wrap things up:

function my_method(variable){
/*
 * 75% of method here
 */
if (variable == 0){
    /* variation one here */
}
else{
    /* variation two here */
}
return value;
}


问:
How to work with a messy codebase and client
A client came to me with some features he wanted implementing. Easy enough to do what he asked. He paid me, I agreed to start on the start date and finish in 3 weeks.

The code base is a disaster. It was coded by Indian freelancers, who have no apparent knowledge of the language. Admittedly, the client said the developers were just copying and pasting code around the web.

There's over 700 files for a relatively simple site. It's the worst code I've ever worked with. No documentation to go by, just lots of files that I have to manually go through.

Before I can even implement a feature I have to clean up parts of the code, simply because it's not possible to work with what they have done.

I've tried to explain to the client that this isn't "as simple as it should be". I am having to refactor and implement features. I'm severely stressed, the deadline is impossible to meet.

The client is constantly on Skype, asking "are we done yet". I try to explain the problems but he don't understand a thing. I offered to redo his site, no additional charge, because the work I'm putting in now is more work than it would be to redo the site. He refused.

I'm at the point where I'm ready to cut my losses, because the money he paid and the stress involved with dealing with this client isn't worth it. It's affecting personal life. My relationship. I have no personal life, because I'm rushing, aimlessly, to meet this deadline, which isn't going to be met.

Any advice please?

答:
One should never allow work to affect your personal life or relationship. If you start feeling like this is the case, something drastic needs to change with either where you work or how you do your work. You need to focus on managing your time & estimating deadlines more accurately.

Next time, consider requesting to do a code review prior to estimating a deadline. At the end of the day, you offered a certain date and seemingly aren't able to meet it. I understand that you didn't realize it was going to be "so much work", however you set the time frame and unfortunately weren't able to deliver. The employer is likely not going to be pleased.

As a professional you have your integrity to handle in a situation like this, so you need to make a decision using your best judgement in terms of moving forwards. You can either:

Request to extend the deadline, or

Offer a refund and abandon the project

Keep in mind, the employer knew that the code base was poor prior to hiring you. You can only do so much with the resources at hand, so don't beat yourself up about it.

But do take things into your own hands and make a concious decision about how you'll be handling situations like this in future. Be fair to yourself and don't allow yourself to fall into this predicament again.


问:
How is ServletContext created?

When the webapp gets loaded the container will create the ServletContext.  There is only one ServletContext per webapp per JVM.

  The ServletContext object is contained within the ServletConfig object which is provided by the web server upon servlet initialisation.

Therefore:

How is ServletContext created by the Container - if it is an interface?

If there is only one ServletContext per webapp and that is provided to ServletConfig (of which there is one per Servlet) then doesn't that mean there is one ServletContext per ServletConfig?

I realize this may seem like a very basic question, but I'm trying to make sure I understand the conceptual aspects involved

答:
1 - each container has its own implementation, which is internal to the container.  For example, in Jetty, the implementation is org.mortbay.jetty.handler.ContextHandler.SContext.

2 - that's the logical conclusion, certainly, but I don't see any reason it needs to be. I would avoid making any assumptions about how many instances of each type of object are created, and just get the appropriate instance through the defined APIs as & when it is required.  It's best not to cache instances of container-created objects, just in case.

Title: How is ServletContext created?


问:
Should a newcomer to Perl learn both Perl 5 and 6?
I have started playing around with Perl 5 lately, and it seems very interesting. I would like to spend some time learning it more in depth when I can.

My question, since Perl 6 is slowly taking place (I believe...) and is said to break backward compatibility, is this: am I better learning Perl 5 and then Perl 6, or is learning Perl 6 directly a better time investment according to you?

If the changes from Perl 5 to 6 are making it hard to understand Perl 5, I should certainly start with Perl 5 to be able to read "old" scripts, then check Perl 6. There is also the "Perl 6 is not yet completely released" problem. I know there's an early adopter implementation for Perl 6, but if Perl 6 isn't officially released before some more years, I'll stick to 5 for now.

I would certainly like some insight on this. Feel free to discuss related stuff. My interest in scripting languages is fairly new.

Thanks!

答:
Perl 5 is the stable line, which will probably develop on a different line than Perl 6. Perl 6 is probably going to have to figure out a new name than Perl.

Perl 6 is, frankly, awesome. But it's not stable enough yet for enterprise use in production (at least, from what I understand). Of course, stable in the enterprise means Perl 5.8 in my experience...


问:
How to avoid violating one definition rule in this case?
We have an existing Mutex C++ class. It has a debug feature to track the owner thread id. So it has a member variable to store this, but because the original developer doesn't want to waste memory, this member is wrapped by a macro in a header file.

This header file has been included in multiple projects, some binaries are developed by other departments, so for those libraries we cannot control the compile flag switch, and we do not want this strong coupling.

```<code>// mutex.h
class Mutex
{
    ......
private:
    #ifdef _DEBUG
    int owner_thread_id_;
    #end
    ......
}
</code>```

Recently we were bitten by this code, because of memory corruption caused by violating the one definition rule.

So how can we implement it with following two requirements:

Don't waste memory because it is a utility class and wide used.

Don't violating the one definition rule.

答:
Simply. Don't mix code built with debug with code built without.

If that class is exported by library you link against, you either need to:

Have debug and release version of the library. That's what one always does on Windows where even the standard runtime has such two versions and they are incompatible, so there is no other way in most cases. This is also the only option if it's third party library you can't fix.

Create debug flag specific to the library and keep a configuration header around setting it as appropriate for the way you built the library.

Leave the field in unconditionally and only make the check conditional (and make sure the all relevant functionality is in functions that get compiled into the library, i.e. defined in .cpp files).

Convert the class to use the PImpl idiom. Then the private fields don't affect ABI.

Ad Edit 1: To prevent linking against the library compiled with different flags than the client code you need to make some symbols be called differently depending on the flag (_DEBUG).

In C++ most suitable method seems to be putting some code in a subnamespace, make that subnamespace be called differently in debug and release configuration, i.e. something like

```<code>#ifdef _DEBUG
namespace library_internal_debug
#else
namespace library_iternal_release
#endif
</code>```

and then import the symbols to the main namespace with similarly conditional using:

```<code>namespace library {
#ifdef _DEBUG
    using library_iternal_debug::stuff;
#else
    using library_iternal_release::stuff;
#endif
</code>```

That way the client will use library::stuff in either configuration, but the actual symbol names will differ, so linking against incorrect build will fail. And unlike renaming with preprocessor this will be properly scoped.

You only need to apply it to one or few important symbols.

Body:
Simply. Don't mix code built with debug with code built without.

If that class is exported by library you link against, you either need to:

Have debug and release version of the library. That's what one always does on Windows where even the standard runtime has such two versions and they are incompatible, so there is no other way in most cases. This is also the only option if it's third party library you can't fix.

Create debug flag specific to the library and keep a configuration header around setting it as appropriate for the way you built the library.

Leave the field in unconditionally and only make the check conditional (and make sure the all relevant functionality is in functions that get compiled into the library, i.e. defined in .cpp files).

Convert the class to use the PImpl idiom. Then the private fields don't affect ABI.

Ad Edit 1: To prevent linking against the library compiled with different flags than the client code you need to make some symbols be called differently depending on the flag (_DEBUG).

In C++ most suitable method seems to be putting some code in a subnamespace, make that subnamespace be called differently in debug and release configuration, i.e. something like

#ifdef _DEBUG
namespace library_internal_debug
#else
namespace library_iternal_release
#endif

and then import the symbols to the main namespace with similarly conditional using:

namespace library {
#ifdef _DEBUG
    using library_iternal_debug::stuff;
#else
    using library_iternal_release::stuff;
#endif

That way the client will use library::stuff in either configuration, but the actual symbol names will differ, so linking against incorrect build will fail. And unlike renaming with preprocessor this will be properly scoped.

You only need to apply it to one or few important symbols.


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

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

Coming back to life after Segmentation Violation

Best practices for recovering from a segmentation fault

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

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

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

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

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

答:
The solution is a remote procedure call. The callee must run in its own process space. How exactly you achieve that is a fairly minor detail. I'd strongly suggest not inventing the wheel yourself.

Not that you'd need this after you've "formally proven its correctness". Correct code doesn't cause segfaults.


问:
How to make sure that the destructor cannot throw an exception?
I know that we can specify the compiler that a function is not throwing an exception by using noexcept specifier but noxecept functions can still throw exceptions . So, how to prevent destructor from throwing an exception ?</p>

答:
If a function is declared as nothrow throws an exception anyway, that is a bug pure and simple.

Given that, to ensure your destructors don't throw any exceptions, there are two paths:

Only call functions that are known not to throw an exception (either because they are declared with nothrow, they are documented not to throw, or they are implemented in a language without exceptions)

Wrap the calls in your destructor that could throw in a try { } catch(...) block.


问:
How to make one test depend on the results of another test?
Let's say there is a utility class that provides some common static methods used everywhere in your code by many other classes.

How would you design your unit tests for the consumers of the utility so that their tests fail if any one of the utility tests do not pass? Can you do it or do you have to check it yourself whether the utility class tests are all green?

For example I have a message-splitter utility that is used (or rather its output) by a message-parser. I'd like to be sure that the message-splitter works correctly before the message-parser gets tested.

I have written tests for both of them but is there a way to link them and make one test depend on the result of some other test?

I couldn't find a suitable tag for this but I'm using Visual Studio's unit test engine.

答:
Try keeping your unit test atomic. Remember that automated testing code is also part of your code base, but is itself not under test, so keep it as simple and obvious as possible.

To answer your question more directly, there is no guarantee of the order of executing of the tests so there is also no way to guarantee that your utility test succeeds before your other tests are run. So there is no guaranteed way to achieve what you want while still having a single test suite for all your tests.

You could move the utilities to their own solution and add a reference to its resulting dll in your current project.


问:
Matrix distribution to process grid
I need to write a program, which will perform LU-decomposition, etc. The problem is that I don't know about the preferred way to distribute the loaded matrix from the root process to other processes. I'm able to create a simple algorithm for some situations, but I really need the solution which works for arbitrary number of processes.

I'd prefer some Coarse-grain distribution according to this presentation (slide 18).

Example

Here I can see, that we can use 1 process or 2 processes (3 or 4 would be "too fine-grain"). But, what's the correct way with 2 processes? Should the matrix be divided by rows or columns?

Example 2

In this case, it's even more problematic. I can't distribute values among 2 processes evenly. Even if I'd distributed it like this:

```<code>P1: 2 8 3 4
P2: 5 1 6 2 5
</code>```

It completely throws the symmetrical distribution into disarray.

Then, with 3 processes it's exactly the same situation like in Example 1 - rows or columns?

So, I presume there is no way to do this for a completely arbitrary number of processes, because the point is in the even distribution. What's the approach for this?

I hope I've described my problem clearly enough. If not, leave a comment, please, and I'll improve my question.

答:
Another solution generally used when performing tasks in parallel is that:

You start by giving the first element to the first process, the second element to the second process,... and the nth element to the nth process.

Once one of the processed finishes the task for the given element, it is given the task to deal with the next element.

Once there are no elements left and all processes finished, the work is done.

This makes the number of elements irrelevant, and targets specifically the cases where you can't be sure that the tasks will take exactly the same duration.

You may have two processes and nine tasks and end up giving eleven tasks to the first process and six to the other, because either some tasks given to the first process were simpler, or because the first process had more CPU cycles available to it.

The same issue (different duration of tasks) applies to most situations where parallel computing is required, such as map-reduce with individual tasks given to different machines (what if one machine has much more powerful hardware than the others?)

Often, the solution is to have many parallel tasks. If you have two tasks and one takes longer than another, there is nothing you can do. If you have twenty tasks and one takes longer, you may compensate by giving additional tasks to the process or machine which doesn't deal with the long-running task.

This also works with tasks which always take the same amount of time, that is a situation where symmetrical distribution is suitable. Imagine, in your example, that each task takes one second. Then the distribution:

```<code>P1: 2 8 3 4
P2: 5 1 6 2 5
</code>```

means that on the overall process which takes five seconds, P1 processing power is wasted during one second, which may be unsuitable (11.1% of wasted processing power). On the other hand, if you have nearly twice as more tasks:

```<code>P1: 2 8 3 4 1 9 8 8 4
P2: 5 1 6 2 5 6 3 1 4 1
</code>```

then P1 wastes one second out of ten seconds, which is slightly better (5.3% waste). Now imagine you have 1 501 equally fast tasks to split between two processes (<0.1%), then the distribution works pretty well, even if it's not symmetrical.

Title: Matrix distribution to process grid

Body:
Another solution generally used when performing tasks in parallel is that:

You start by giving the first element to the first process, the second element to the second process,... and the nth element to the nth process.

Once one of the processed finishes the task for the given element, it is given the task to deal with the next element.

Once there are no elements left and all processes finished, the work is done.

This makes the number of elements irrelevant, and targets specifically the cases where you can't be sure that the tasks will take exactly the same duration.

You may have two processes and nine tasks and end up giving eleven tasks to the first process and six to the other, because either some tasks given to the first process were simpler, or because the first process had more CPU cycles available to it.

The same issue (different duration of tasks) applies to most situations where parallel computing is required, such as map-reduce with individual tasks given to different machines (what if one machine has much more powerful hardware than the others?)

Often, the solution is to have many parallel tasks. If you have two tasks and one takes longer than another, there is nothing you can do. If you have twenty tasks and one takes longer, you may compensate by giving additional tasks to the process or machine which doesn't deal with the long-running task.

This also works with tasks which always take the same amount of time, that is a situation where symmetrical distribution is suitable. Imagine, in your example, that each task takes one second. Then the distribution:

P1: 2 8 3 4
P2: 5 1 6 2 5

means that on the overall process which takes five seconds, P1 processing power is wasted during one second, which may be unsuitable (11.1% of wasted processing power). On the other hand, if you have nearly twice as more tasks:

P1: 2 8 3 4 1 9 8 8 4
P2: 5 1 6 2 5 6 3 1 4 1

then P1 wastes one second out of ten seconds, which is slightly better (5.3% waste). Now imagine you have 1 501 equally fast tasks to split between two processes (<0.1%), then the distribution works pretty well, even if it's not symmetrical.


问:
PHP MVC Model with a method to fetch all of the model from database
I have a crazy question, consider I'm developing a blog website, There is two model named Post and Comment, now I wanna add a method to fetch all comments from database, which model should I choose to add this method to? Post or Comment.

Approach 1:

```<code>$post= new Post();
$post->setID($id);
$r = $post->loadAllComments();
</code>```

Approach 2:

```<code>$r = Comment::loadAllComments($post_id);
</code>```

答:
I would use approach 2, putting it on the Comment model. I'd name the method something like loadAllCommentsForPost though, to clarify that it doesn't just load every single comment from the database.

Though approach 1 wouldn't be too bad, consider that you might have a lot more models relating to Post later on. You wouldn't want your Post model cluttered with methods like loadAllLikes and loadAllRetweets. It would be much cleaner to split those up to their respective models - Likes and Retweets.


答:
If you are always using sectioning elements (wherever they are needed), it doesn’t matter which heading element (h1-h6) you choose. The outline algorithm "calculates" the correct heading rank, which depends on the nesting of your sectioning elements.

It’s not "less semantic". Don’t think of HTML5 headings as h1-h6, but as h (AFAIK such an h element wasn’t added to HTML5 because we’d lose backward compatibility; but XHTML 2.0 went this way).

You have two options:

Use h1 everywhere (instead of h1, it could be any other heading element, and even a mix of them).

Use heading elements of the "calculated" rank, like in HTML 4.01.

Advantages of the first option:

You can freely insert (e.g. from external sources) and move sections, without having to adjust the markup.

You can have more than 6 levels.

Advantage of the second option:

It supports user agents that don’t have implemented this outline algorithm.

Note that HTML5 encourages authors to use the second option.

Title: Semantics of heading levels in multiple sections in HTML5

Body:
I'm never quite sure what is the best, most semantic way to handle heading levels in HTML5 markup, when you have multiple sections. On one hand it makes sense to have an H1 heading as a title of a section, or an article, but it leads to these weird situations when your whole document outline is made out of H1 headings.

```<code><header>
    <h1>Site heading</h1>
</header>
...
<section>
    <h1>Section heading</h1>
    <article>
        <h1>Article heading</h1>
        ...
    </article>
    ...
    <section>
        <h1>Subsection heading</h1>
        <article>
            <h1>Subsection article heading</h1>
            ...
        </article>
        ...
    </section>
</section>
</code>```

Is this really the way to do it in HTML5? It feels a bit like the heading tags don't carry no semantic value anymore. When you see an H1 tag in a markup it doesn't tell you anything about the headings position in the document's outline.

On the other hand, when you mark your headings hierarchically, like you would before the HTML5's markup, it creates a situations where one article has a different heading level than another, while having the same level as a subsection, which also doesn't make much sense.

```<code><header>
    <h1>Site heading</h1>
</header>
...
<section>
    <h2>Section heading</h2>
    <article>
        <h3>Article heading</h3>
        ...
    </article>
    ...
    <section>
        <h3>Subsection heading</h3>
        <article>
            <h4>Subsection article heading</h4>
            ...
        </article>
        ...
    </section>
</section>
</code>```

From what I read, I understand that the first way is the correct way in HTML5, but it just doesn't feel right. Having often a whole site without single third level heading feels weird, but it might be just a case of old habits dying hard on my part, maybe?


问:
Chat-service database design
I have an android/desktop application that I'm now releasing on the web and, as there are some social aspects, I thought of adding a chat-service so users can IM as well.
For this chat service, I want people to have "Online, Offline, Busy and Away" as possible statuses.

I currently have a table in my database named "users", which has their username/password/mail etc, all the usual stuff. Now I was wondering whether I need to save the status of the user here as well?

If not: How do I best store a user's status? (Keeping in mind others need to see this of course)

If yes: What's the best way to go about this? I thought I would store it as an integer (e.g, 1==offline, 2==online, 3==away and 4==busy). Saving it as text would just be a waste of space?

(By the way, it's an RDBMS, if that matters :) )

答: I agree with you, storing the status as integer will be enough. And I would prefer store it in different table, let's say user_status, since it will be updated frequently according to user activities.</p>

Title: Chat-service database design


问:
Should I focus on being deep or broad
I have been a professional developer for just over half a year and have been amazed at how big the world really is out of college. I have continued to learn in my free time but I am wondering where should I focus?

FOCUS 1) The development stack used by my company. Quickest payoff in my day to day development. #Deepest

FOCUS 2) A different language with the same paradigm. See if I can generalize my knowledge and way of thinking.

FOCUS 3) Different language, different paradigm. Expand my borders and learn new ways to do things. #Broadest

If anyone has a different focus feel free to put that out there.

答:
Go ahead and learn something like Haskell or a Lisp.  Learning a functional language has really though me to decouple my code, making it simpler to debug overall.  The only problem you might encounter is that you don't want to go back.

http://book.realworldhaskell.org/read/

http://lisperati.com/haskell/

http://learnyouahaskell.com/

Title: Should I focus on being deep or broad


问:
Constructor-only subclasses: Is this an anti-pattern?
I was having a discussion with a co-worker, and we ended up having conflicting intuitions about the purpose of subclassing. My intuition is that if a primary function of a subclass is to express a limited range of possible values of its parent, then it probably shouldn't be a subclass. He argued for the opposite intuition: that subclassing represents an object's being more "specific", and therefore a subclass relationship is more appropriate.

To put my intuition more concretely, I think that if I have a subclass that extends a parent class but the only code that subclass overrides is a constructor (yes, I know constructors don't generally "override", bear with me), then what was really needed was a helper method.

For example, consider this somewhat real-life class:

public class DataHelperBuilder
{
    public string DatabaseEngine { get; set; }
    public string ConnectionString { get; set; }

    public DataHelperBuilder(string databaseEngine, string connectionString)
    {
        DatabaseEngine = databaseEngine;
        ConnectionString = connectionString;
    }

    // Other optional "DataHelper" configuration settings omitted

    public DataHelper CreateDataHelper()
    {
        Type dataHelperType = DatabaseEngineTypeHelper.GetType(DatabaseEngine);
        DataHelper dh = (DataHelper)Activator.CreateInstance(dataHelperType);
        dh.SetConnectionString(ConnectionString);

        // Omitted some code that applies decorators to the returned object
        // based on omitted configuration settings

        return dh;
    }
}
```

<p>His claim is that it would be entirely appropriate to have a subclass like this:</p>

<pre class="lang-cs prettyprint-override"><code>public class SystemDataHelperBuilder
{
    public SystemDataHelperBuilder()
        : base(Configuration.GetSystemDatabaseEngine(),
               Configuration.GetSystemConnectionString())
    {
    }
 }
</code>```

So, the question:

Among people who talk about design patterns, which of these intuitions is correct? Is subclassing as described above an anti-pattern?

If it is an anti-pattern, what is its name?

I apologize if this turns out to have been an easily googleable answer; my searches on google mostly returned information about the telescoping constructor anti-pattern and not really what I was looking for.

答:
The most common use of such subclasses that I can think of is exception hierarchies, although that's a degenerate case where we would typically define nothing at all in the class, as long as the language lets us inherit constructors. We use inheritance to express that ReadError is a special case of IOError, and so on, but ReadError need not override any methods of IOError.

We do this because exceptions are caught by checking their type. Thus, we need to encode the specialisation in the type so that someone can catch only ReadError without catching all IOError, should they want to.

Normally, checking the types of things is terribly bad form and we try to avoid it. If we succeed in avoiding it, then there's no essential need to express specialisations in the type system.

It might still be useful though, for example if the name of the type appears in the logged string form of the object: this is language and possibly framework specific. You could in principle replace the name of the type in any such system with a call to a method of the class, in which case we would override more than just the constructor in SystemDataHelperBuilder, we'd also override loggingname(). So if there's any such logging in your system you could imagine that although your class literally only overrides the constructor, "morally" it's also overriding the class name, and so for practical purposes it isn't a constructor-only subclass. It has desirable different behaviour, it's just that you get this behaviour for free without writing any method overrides thanks to cunning use of reflection elsewhere.

So, I would say that his code can be a good idea if there's some code elsewhere that somehow checks for instances of SystemDataHelperBuilder, either explicitly with a branch (like exception catching branches based on type) or perhaps because there's some generic code that will end up using the name SystemDataHelperBuilder in a useful way (even if it's just logging).

However, using types for special cases does lead to some confusion, since if ImmutableRectangle(1,1) and ImmutableSquare(1) behave differently in any way then eventually someone is going to wonder why and perhaps wish it didn't. Unlike exception hierarchies, you check whether a rectangle is a square by checking whether height == width, not with instanceof. In your example, there's a difference between a SystemDataHelperBuilder and a DataHelperBuilder created with the exact same arguments, and that has potential to cause problems. Therefore, a function to return an object created with the "right" arguments seems to me normally the right thing to do: the subclass results in two different representations of "the same" thing, and it only helps if you're doing something you normally would try not to do.

Note that I'm not talking in terms of design patterns and anti-patterns, because I don't believe that it's possible to provide a taxonomy of all good and bad ideas that a programmer has ever thought of. Thus, not every idea is a pattern or anti-pattern, it only becomes that when someone identifies that it occurs repeatedly in different contexts and names it ;-) I'm not aware of any particular name for this kind of subclassing.


答:
```<code>... table in my database named "users", which has their username/password/mail etc,
</code>```

Of course you mean that you're storing the "hashed" or similarly calculated value derived from the user's chosen password.

```<code>How do I best store a users status?
</code>```

I would go with an Integer value in the users record, which is a foreign key to a (tiny, little) look-up table of users_statuses:

```<code>status_id  Description
        1  Offline
        2  Online
        3  Away
        4  Busy
</code>```

That way, when you want to add ...

```<code>       37  Lost in the Bermuda Triangle
</code>```

... it's just another row in a table; no code changes; no database schema changes; easy.

Title: Chat-service database design

Body:
I have an android/desktop application that I'm now releasing on the web and, as there are some social aspects, I thought of adding a chat-service so users can IM as well.
For this chat service, I want people to have "Online, Offline, Busy and Away" as possible statuses.

I currently have a table in my database named "users", which has their username/password/mail etc, all the usual stuff. Now I was wondering whether I need to save the status of the user here as well?

If not: How do I best store a user's status? (Keeping in mind others need to see this of course)

If yes: What's the best way to go about this? I thought I would store it as an integer (e.g, 1==offline, 2==online, 3==away and 4==busy). Saving it as text would just be a waste of space?

(By the way, it's an RDBMS, if that matters :) )

Body:
... table in my database named "users", which has their username/password/mail etc,

Of course you mean that you're storing the "hashed" or similarly calculated value derived from the user's chosen password.

How do I best store a users status?

I would go with an Integer value in the users record, which is a foreign key to a (tiny, little) look-up table of users_statuses:

status_id  Description
        1  Offline
        2  Online
        3  Away
        4  Busy

That way, when you want to add ...

       37  Lost in the Bermuda Triangle

... it's just another row in a table; no code changes; no database schema changes; easy.


问:
Why is Android Runtime's AOT compilation more performant than Dalvik's JIT?
With Android 5.0, Google has introduced the Android Runtime, or ART. ART "brings improvements in performance, garbage collection, applications debugging and profiling." However, it also replaces Dalvik's Just-in-Time compilation with Ahead-of-Time compilation performed by translating the Dalvik bytecode to a native ELF executable at application install time.

My question is: what were Google's technical reasons for making this choice and why is it more performant? I've long been an advocate of native code over managed code, but even so, I thought that JIT'd code could outperform AOT-compiled code in many or perhaps even most situations due to its ability to re-optimize for actual application behavior at runtime.

Are the advantages of AOT specific to Android's implementation or environment (i.e. mobile devices with ARM CPUs and limited RAM), or was JIT just oversold?

答:
Compilers need two things to generate performant code: information and resources.

JIT compilers have way more information at their disposal than AOT compilers. Static analysis is impossible in the general case (nearly everything interesting you would want to know about a program can be reduced to either the Halting Problem or Rice's Theorem), and hard even in the special case. JIT compilers don't have this problem: they don't have to statically analyze the program, they can observe it dynamically at runtime.

Plus, a JIT compiler has techniques at its disposal that AOT compilers don't, the most important one being de-optimization. Now, you might think, we is de-optimization important for performance? Well, if you can de-optimize, then you can be over-aggressive in making optimizations that are actually invalid (like inlining a method call that may or may not be polymorphic), and if it turns out that you are wrong, you can then de-optimize back to the un-inlined case (for example).

However, there's the problem of resources: an AOT compiler can take as much time as it wants, and use as much memory as it wants. A JIT compiler has to steal its resources away from the very program that the user wants to use right now.

Normally, that is not a problem. Our today's machines are so ridiculously overpowered, that there are always enough resources at the JIT's disposal. Especially since the JIT will use the most resources when a lot of new code is introduced into the system at once, which is usually during program startup, or when the program transitions between phases (for example, from parsing the configuration files to setting up the object graph, or from finishing configuration to starting the actual work), at which times the program itself typically does not yet use that many resources (especially during program startup). The Azul JCA is a good example. It has 864 cores and 768 GiByte RAM in its biggest configuration (and note that they haven't been sold for quite some time, so that is actually several years old technology). According to Azul's measurements, the JIT uses maybe 50 cores, when it is working very hard. That's still more than 800 cores leftover for the program, the system and the GC.

But your typical Android device doesn't have 1000 cores and a TiByte of RAM. And it is extremely interactive and latency-sensitive, when the user starts, say, WhatsApp, he wants to write a message right now. Not in 500msec, when the JIT has warmed up. NOW.

That's what makes AOT attractive here. Also note that JIT compiling will not only steal resources away from the running program, it will also need battery power, and it will need that every time the program runs, whereas an AOT compiler will only need to spend that power budget once, when the app is installed.

You could go even more extreme and push the compilation off to the app store or even to the developer, like Apple does, but Apple has the advantage of a much more limited set of possible target platforms to consider, so on-device AOT compilation seems a reasonable trade-off for Android.


问:
Methods of ordering function definitions in code
When I work on some programming project (usually command line application in Python with many switches), I'm usually creating about 30 and more functions. Most of the functions are in one file (except some helpers that I utilize in more projects).

Some of the functions are called on particular switch (like -p or --print) but many functions do some helper computations, print operations or database operations because I don't want to main functions be too large.

When I have an idea for a new functionality I often put new functions randomly to the file. Should I think more about it and place it to some particular place? Are there some methods for this?

答:
Maybe it's force of habit from C coding 20+ years ago, but, no matter what the language, I usually let my small helper functions float to the top.

At the very least, I like to have every function declared before it is called, in order to obviate the need for forward declaration/function prototypes.

I guess that makes me the exact opposite of @IAE (+1 to him anyway ;-), although I do sometimes exactly mirror his approach, having helpers directly above the function which calls them.

If helpers are specific to one function and the language allows nested functions, there is much to be said for nesting the helpers inside of the function which utilizes them.


答:
The users table is definitely the place to store it.

Note that if you use MySql (and possibly some others?), you can also use an enum, so that you can be sure that the value that you write is in range, and you can refer it to it legibly in your application's code (e.g., onLine, instead of 1).

Title: Chat-service database design


问:
How to design a solution that needs dynamism using Inheritance
I have below code/classes/interfaces:

An Interface:

```<code> public interface Animal<A extends Animal<A>>{
 void fight(A otherAnimal);
 }
</code>```

2.Tiger class which is implementing Animal

```<code>    public class Tiger implements Animal{
    @Override
    public void fight(Tiger otherAnimal) {
        System.out.println("Tiger Fights");
    }
}
</code>```

3. I have a Lion class which also implements Animal

```<code>  Public class Lion implements Animal{
 @Override
 public void fight(Lion otherAnimal) {
    System.out.println("Lion Fights");
}
</code>```

I have a test class which is going to call fight:

```<code>public class TestClass{
public static void main(String[] args){
   Animal tiger = new Tiger();
   Animal lion = new Lion();
   tiger.fight(lion);
   }
}
</code>```

Now when I run the test class the obvious output is "Tiger Fights".

How should I redesign so that when I call fight on tiger with anything other than tiger should call their respective classes.

So in the example above it should invoke lion's fight even if the fight is called on object of tiger.

I need output as "lion fights" even if I am invoking an object of tiger. Meaning actually I want developer to have freedom to pass any type of object to to any class. My expectation is based on type of object the respective overridden method has to be called.

I need this dynamism because there can be N number of different animals (cat, dog, wolf etc) which might get added in near future.

Is it possible to design in such a way that My Animal interface will decide which class to call depending of type of object passed?

答:
First of all, you're setting up Animal interface with generics in order to make the Animal instance passed to fight as the same as the one implementing Animal.  In other words, Lion can only fight a Lion.  A Tiger can only fight a Tiger.  From the sounds of it, you want to be able to fight any animal.  If you don't need to use A for any other reason in interface, ditch it.  It isn't helpful.

```<code>public interface Animal {
  void fight(Animal otherAnimal);
}
</code>```

Second, now that you're receiving an Animal instance, you need to know if it is an instance of the very same class implementing Animal.

To do this, you could simply write:

```<code>public class Tiger implements Animal{
    @Override
    public void fight(Animal otherAnimal) {
        if(otherAnimal.getClass().equals(this.getClass()) {
            System.out.println("Two tigers fight");
        } else {
            System.out.println("Tiger fights a " + otherAnimal.getClass().getName());
        }
    }
}
</code>```

This works fine so long as you don't need to know what type otherAnimal is.  In other words, if you start constructing if.. else lists to cover every possibility, you're doing it wrong.  Tiger should know how it fights other animals, and anything that might change the outcome should be something that all Animal instances have.

For instance, if you want to attack "Pokemon" style with each animal having its own health bar, you need not cast it to Lion to get the Lion's health points.  You need only create a "getHealthPoints" method in Animal.

If you're using Java 8, you can even make use of defaults in your interface and override only if your subclass needs to behave differently:

```<code>public interface Animal {
  default void fight(Animal otherAnimal) {
     if(otherAnimal.getClass().equals(this.getClass()) {
         System.out.println("Two " + this.getClass().getName() + "s fight");
     } else {
         System.out.println(this.getClass().getName() + " fights a " + otherAnimal.getClass().getName());
     }
  }
}
</code>```

For this particular example, this should be sufficient, though if you're looking for an example of Visitor pattern, the wikipedia article on Visitor pattern provides a decent explanation.  Note that the structure is more hierarchical and serves primarily for performing an operation on each object in it.  This would be a bit of an overkill for this particular instance, so I won't modify the above example.

Hope that helps.

Body:
First of all, you're setting up Animal interface with generics in order to make the Animal instance passed to fight as the same as the one implementing Animal.  In other words, Lion can only fight a Lion.  A Tiger can only fight a Tiger.  From the sounds of it, you want to be able to fight any animal.  If you don't need to use A for any other reason in interface, ditch it.  It isn't helpful.

public interface Animal {
  void fight(Animal otherAnimal);
}

Second, now that you're receiving an Animal instance, you need to know if it is an instance of the very same class implementing Animal.

To do this, you could simply write:

public class Tiger implements Animal{
    @Override
    public void fight(Animal otherAnimal) {
        if(otherAnimal.getClass().equals(this.getClass()) {
            System.out.println("Two tigers fight");
        } else {
            System.out.println("Tiger fights a " + otherAnimal.getClass().getName());
        }
    }
}

This works fine so long as you don't need to know what type otherAnimal is.  In other words, if you start constructing if.. else lists to cover every possibility, you're doing it wrong.  Tiger should know how it fights other animals, and anything that might change the outcome should be something that all Animal instances have.

For instance, if you want to attack "Pokemon" style with each animal having its own health bar, you need not cast it to Lion to get the Lion's health points.  You need only create a "getHealthPoints" method in Animal.

If you're using Java 8, you can even make use of defaults in your interface and override only if your subclass needs to behave differently:

public interface Animal {
  default void fight(Animal otherAnimal) {
     if(otherAnimal.getClass().equals(this.getClass()) {
         System.out.println("Two " + this.getClass().getName() + "s fight");
     } else {
         System.out.println(this.getClass().getName() + " fights a " + otherAnimal.getClass().getName());
     }
  }
}

For this particular example, this should be sufficient, though if you're looking for an example of Visitor pattern, the wikipedia article on Visitor pattern provides a decent explanation.  Note that the structure is more hierarchical and serves primarily for performing an operation on each object in it.  This would be a bit of an overkill for this particular instance, so I won't modify the above example.

Hope that helps.


问:
Why are structs and classes separate concepts in C#?
While programming in C#, I stumbled upon a strange language design decision that I just can't understand.

So, C# (and the CLR) has two aggregate data types: struct (value-type, stored on the stack, no inheritance) and class (reference-type, stored on the heap, has inheritance).

This setup sounds nice at first, but then you stumble upon a method taking a parameter of an aggregate type, and to figure out if it is actually of a value type or of a reference type, you have to find its type's declaration. It can get really confusing at times.

The generally accepted solution to the problem seems to be declaring all structs as "immutable" (setting their fields to readonly) to prevent possible mistakes, limiting structs' usefulness.

C++, for example, employs a much more usable model: it allows you to create an object instance either on the stack or on the heap and pass it by value or by reference (or by pointer). I keep hearing that C# was inspired by C++, and I just can't understand why didn't it take on this one technique. Combining class and struct into one construct with two different allocation options (heap and stack) and passing them around as values or (explicitly) as references via the ref and out keywords seems like a nice thing.

The question is, why did class and struct become separate concepts in C# and the CLR instead of one aggregate type with two allocation options?

答:
This is from "C#: Why Do We Need Another Language?" - Gunnerson, Eric:

Simplicity was an important design goal for C#.

It's possible to go overboard on simplicity and language purity but
  purity for purity's sake is of little use to the professional
  programmer. We therefore tried to balance our desire to have a simple
  and concise language with solving the real-world problems that
  programmers face.

[...]

Value types, operator overloading and user-defined conversions all add
  complexity to the language, but allow an important user scenario to be
  tremendously simplified.

Reference semantics for objects is a way to avoid a lot of troubles (of course and not only object slicing) but real world problems can sometimes require objects with value semantic (e.g take a look at Sounds like I should never use reference semantics, right? for a different point of view).

What better approach to take, therefore, than segregate those dirty, ugly and bad objects-with-value-semantic under the tag of struct?


答:
If you are looking for a class for code that calls a winner of 2 animals fighting, then the solution is a third class that does that. Imagine you have to write a compare method that compares objects of 10 very different classes. Obviously you can't have code doing the comparing spread out all over those 10 classes. It's much cleaner to write a Comparator class.

If you are just asking how to write code x operation y where you can code operation for each x and y type pair separately then you're looking for dual dispatch, usually implemented by Visitor pattern.

Edit: you are also misusing generic types. You are adding generic type of A to whole Animal type just for the target type of fight method. You should add generic type to the method only.

The correct declaration of animal would be:

```<code>public interface Animal {
    <A extends Animal> void fight(A otherAnimal);
}
</code>```

Title: How to design a solution that needs dynamism using Inheritance

Body:
I have below code/classes/interfaces:

An Interface:

```<code> public interface Animal<A extends Animal<A>>{
 void fight(A otherAnimal);
 }
</code>```

2.Tiger class which is implementing Animal

```<code>    public class Tiger implements Animal{
    @Override
    public void fight(Tiger otherAnimal) {
        System.out.println("Tiger Fights");
    }
}
</code>```

3. I have a Lion class which also implements Animal

```<code>  Public class Lion implements Animal{
 @Override
 public void fight(Lion otherAnimal) {
    System.out.println("Lion Fights");
}
</code>```

I have a test class which is going to call fight:

```<code>public class TestClass{
public static void main(String[] args){
   Animal tiger = new Tiger();
   Animal lion = new Lion();
   tiger.fight(lion);
   }
}
</code>```

Now when I run the test class the obvious output is "Tiger Fights".

How should I redesign so that when I call fight on tiger with anything other than tiger should call their respective classes.

So in the example above it should invoke lion's fight even if the fight is called on object of tiger.

I need output as "lion fights" even if I am invoking an object of tiger. Meaning actually I want developer to have freedom to pass any type of object to to any class. My expectation is based on type of object the respective overridden method has to be called.

I need this dynamism because there can be N number of different animals (cat, dog, wolf etc) which might get added in near future.

Is it possible to design in such a way that My Animal interface will decide which class to call depending of type of object passed?

Body:
If you are looking for a class for code that calls a winner of 2 animals fighting, then the solution is a third class that does that. Imagine you have to write a compare method that compares objects of 10 very different classes. Obviously you can't have code doing the comparing spread out all over those 10 classes. It's much cleaner to write a Comparator class.

If you are just asking how to write code x operation y where you can code operation for each x and y type pair separately then you're looking for dual dispatch, usually implemented by Visitor pattern.

Edit: you are also misusing generic types. You are adding generic type of A to whole Animal type just for the target type of fight method. You should add generic type to the method only.

The correct declaration of animal would be:

public interface Animal {
    <A extends Animal> void fight(A otherAnimal);
}


问:
2 methods that are 75% the same?
I have code that violates the DRY principle and I would like to consolidate 2 methods as much as I can, but the problem I am facing is that they have some differences, I would say they are about 75% the same, but the other 25% is different in certain areas.  What kinds of design patterns or design approaches can I do to turn 2 methods into 1 or at least limit the code needed in each, so that they become more scalable and maintainable?

答:
One common way to refactor code like this is through inheritance, using abstract or virtual methods for the behavior that may vary.

Let's say you have a method to pay employees, and another one to pay the CEO:

void PayNormalEmployee()
{
    // do stuff
    // do more stuff
    // give meager bonus
    // do final stuff
}

void PayCeo()
{
    // do stuff
    // do more stuff
    // give huge bonus
    // do final stuff
}
```

<p>Let's assume that you have to do things in the order above; you can't just reorder to set the bonus part as the last step.</p>

<p>The way to refactor this is through inheritance.  You put the common behavior in a base class, and put the distinct behavior in distinct subclasses.  Your common line (or set of lines) should call out to a separate method.  For instance:</p>

<pre class="lang-cs prettyprint-override"><code>abstract class EmployeeBase
{
    public void Pay()
    {
        // do stuff
        // do more stuff
        PayBonus();
        // do final stuff
    }

    protected abstract void PayBonus();
}

class NormalEmployee : EmployeeBase
{
    override void PayBonus()
    {
        // pay meager bonus
    }
}

class Ceo : EmployeeBase
{
    override void PayBonus()
    {
        // pay huge bonus
    }
}
</code>```

Whether your employee is a NormalEmployee or a CEO, he/she has access to the Pay method, but the implementation in the derived class will be used.

If there's a "default" implementation, you can make this simpler:

class Employee
{
    public void Pay()
    {
        // do stuff
        // do more stuff
        PayBonus();
        // do final stuff
    }

    protected virtual void PayBonus()
    {
        // pay meager bonus
    }
}

class Ceo : Employee
{
    override void PayBonus()
    {
        // pay huge bonus
    }
}
```

Again, the CEO has access to the Pay method, but will use his/her special PayBonus implementation; but everything will still happen in the proper order.

Title: 2 methods that are 75% the same?

Body:
One common way to refactor code like this is through inheritance, using abstract or virtual methods for the behavior that may vary.

Let's say you have a method to pay employees, and another one to pay the CEO:

void PayNormalEmployee()
{
    // do stuff
    // do more stuff
    // give meager bonus
    // do final stuff
}

void PayCeo()
{
    // do stuff
    // do more stuff
    // give huge bonus
    // do final stuff
}

Let's assume that you have to do things in the order above; you can't just reorder to set the bonus part as the last step.

The way to refactor this is through inheritance.  You put the common behavior in a base class, and put the distinct behavior in distinct subclasses.  Your common line (or set of lines) should call out to a separate method.  For instance:

abstract class EmployeeBase
{
    public void Pay()
    {
        // do stuff
        // do more stuff
        PayBonus();
        // do final stuff
    }

    protected abstract void PayBonus();
}

class NormalEmployee : EmployeeBase
{
    override void PayBonus()
    {
        // pay meager bonus
    }
}

class Ceo : EmployeeBase
{
    override void PayBonus()
    {
        // pay huge bonus
    }
}

Whether your employee is a NormalEmployee or a CEO, he/she has access to the Pay method, but the implementation in the derived class will be used.

If there's a "default" implementation, you can make this simpler:

class Employee
{
    public void Pay()
    {
        // do stuff
        // do more stuff
        PayBonus();
        // do final stuff
    }

    protected virtual void PayBonus()
    {
        // pay meager bonus
    }
}

class Ceo : Employee
{
    override void PayBonus()
    {
        // pay huge bonus
    }
}

Again, the CEO has access to the Pay method, but will use his/her special PayBonus implementation; but everything will still happen in the proper order.


问:
Is there a canonical book on Ruby on Rails?
I'm an experienced developer with .NET, and understand core computing concepts well (OOP, design patterns, etc) but would like to also learn rails.

Is there a book out there that's the de-facto standard for describing best practices, design methodologies, and other helpful information on Ruby on Rails? What about that book makes it special?

答:
I would recommend The Rails 3 Way by Obie Fernandez if you're really interested in learning Rails in depth, and learn how the 'magic' happens behind the scenes.

If you'd like the learn just for the sake of it or create a simple app, Agile Web Development with Rails by Sam Ruby, Dave Thomas & David Heinemeier Hansson should work out just fine.