答:
No, absolutely not!

In general, you should never "anticipate". Predictions are hard, especially those concerning the future. APIs should be extracted from working code, not pulled out of thin air. Follow YAGNI, follow the Rule of Three (don't extract an API until you have three independent clients).

In this particular case, even if you had three clients, a file name sanitizing API has no business being in an email library. It belongs in a file name library.

Title: Should public API classes have helper methods that provide anticipated functionality?

Body:
For the purposes of providing a concrete example for my question, let's say I'm building an API that provides access to an email system and contains a set of public classes e.g. Mailbox, MailboxFolder, Message, MessageAttachment, and so on.

Is it a good idea to try to anticipate how clients may use the API and provide "helper" methods for common operations?

For example, imagine my Message class has a Save(string toFilePath) method.  Maybe it would be helpful to provide another method in Message that builds a "safe file name" from the subject of the message, i.e. a file name that is some reasonable portion of the subject (since the length of an email subject can far exceed the maximum length of a file path) where all characters that are not valid for use in a file name have been replaced with a usable character.

The reason for this would be that I anticipate clients may often want to save an email with a name that resembles the subject.


问:
How do I resolve $ref in a JSON object?
I have written a single page application that uses rest services to retrieve JSON objects.  The JSON objects being returned are C# objects serialized using the Newtonsoft.JSON library.  The returned JSON object contains $ref pointers to specific $id objects within the same JSON object (The question here shows an example).  I need to access the actual data that the $ref points to, but I do not know how to access it without locating the original source.

I've found solutions such as writing a new contract serializer and writing my own implementation of resolving the references.  I feel like there should be an easier solution than these two.  I've also explored the Newtonsoft JSON serialization settings; I've tried setting PreserveReferenceHandling to None, but I haven't had any success there.

I'm looking for solutions other than the ones I've mentioned.  I'm hoping there's a simple solution that requires very little code to implement and no additional frameworks.

UPDATE

I've been reading some more about this and discovered that $ref is a JSON Pointer fragment.  The reference number is an ID that references an item from a different schema.  That appears to be the solution, but a schema needs to be defined for it to work.

RFC for JSON Pointer Fragments

Info about JSON Pointer Fragments

References:

Resolve circular JSON references

Serialization Settings

答:
I was able to resolve the "$ref" links in my json code by adapting the code, this blogger posted, to be Angular compliant.

http://willseitz-code.blogspot.com/2013/01/javascript-to-deserialize-json-that.html

I created an angular service to resolve the "$ref" I get from NewtonSofts JSON serializer.

```<code>// http://willseitz-code.blogspot.com/2013/01/javascript-to-deserialize-json-that.html
(function () {
'use strict';

angular
    .module('app')
    .factory('jsonPointerParseService', jsonPointerParseService);

jsonPointerParseService.$inject = [];

function jsonPointerParseService() {
    var hashOfObjects = {};

    var service = {
        pointerParse: pointerParse
    };

    return service;

    function collectIds(obj) {
        if (jQuery.type(obj) === "object") {
            if (obj.hasOwnProperty("$id")) {
                hashOfObjects[obj.$id] = obj;
            }
            for (var prop in obj) {
                collectIds(obj[prop]);
            }
        } else if (jQuery.type(obj) === "array") {
            obj.forEach(function (element) {
                collectIds(element);
            });
        }
    }

    function setReferences(obj) {
        if (jQuery.type(obj) === "object") {
            for (var prop in obj) {
                if (jQuery.type(obj[prop]) === "object" &&
                    obj[prop].hasOwnProperty("$ref")) {
                    obj[prop] = hashOfObjects[obj[prop]["$ref"]];
                } else {
                    setReferences(obj[prop]);
                }
            }
        } else if (jQuery.type(obj) === "array") {
            obj.forEach(function (element, index, array) {
                if (jQuery.type(element) === "object" &&
                    element.hasOwnProperty("$ref")) {
                    array[index] = hashOfObjects[element["$ref"]];
                } else {
                    setReferences(element);
                }
            });
        }
    }

    // Set the max depth of your object graph because JSON.stringify will not be able to
    // serialize a large object graph back to
    function setMaxDepth(obj, depth) {
        // If this is not an object or array just return there is no need to
        // set its max depth.
        if (jQuery.type(obj) !== "array" && jQuery.type(obj) !== "object") {
            return obj;
        }

        var newObj = {};

        // If this object was an array we want to return the same type in order
        // to keep this variable's consistency.
        if (jQuery.type(obj) === "array") {
            newObj = [];
        }

        // For each object or array cut off its tree at the depth value by
        // recursively diving into the tree.
        angular.forEach(obj, function (value, key) {
            if (depth == 1) {
                newObj = null;
            }
            else if (jQuery.type(value) === "array") {
                if (setMaxDepth(value, depth - 1)) {
                    newObj[key] = setMaxDepth(value, depth - 1)
                } else {
                    newObj = [];
                }
            } else if (jQuery.type(value) === "object") {
                if (setMaxDepth(value, depth - 1)) {
                    newObj[key] = setMaxDepth(value, depth - 1)
                } else {
                    newObj = [];
                }
            } else {
                newObj[key] = value;
            }
        }, newObj);

        return newObj;
    }

    function pointerParse(obj, depth) {
        var newObj = obj;

        hashOfObjects = {};
        collectIds(newObj);
        setReferences(newObj);

        if (depth) {
            newObj = setMaxDepth(newObj, depth);
        }

        return newObj;
    }
}
})();
</code>```

Usage would be like so:

```<code> var newObj = jsonPointerParseService.pointerParse(obj);
</code>```

Please keep in mind, this is an Angular service.  So I inject it into whichever controller needs to have these references resolved, and make the call to pointerParse() accordingly.

Please note though that if you want to post this object back to the server, your browsers JSON.stringify() call has to be able to handle an object with circular references.  By default, in my case, Angular does not call JSON.stringify() with the parameters required to be able to stringify an object with circular references.  So, in this case I would suggest posting only a small portion of data and not this entire object back or instantiating your own call to stringify an object like this.

Lastly, I must say that dealing with $ref is a pain and I decided to preserve reference handling with only arrays.  This seemed to work well for me.  I still had to access array values with $values however I didnt have to worry about resolving references and didnt have to worry about the server blowing up trying to serialize all of the object circular references to json.

```<code>json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize;

json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Arrays;
</code>```

Update: Even with only resolving arrays there are still references that you may need to resolve. In those instances use the pointerParse() function to take care of them.

ContentLicense: CC BY-SA 3.0

Title: How do I resolve $ref in a JSON object?

Body:
I was able to resolve the "$ref" links in my json code by adapting the code, this blogger posted, to be Angular compliant.

http://willseitz-code.blogspot.com/2013/01/javascript-to-deserialize-json-that.html

I created an angular service to resolve the "$ref" I get from NewtonSofts JSON serializer.

// http://willseitz-code.blogspot.com/2013/01/javascript-to-deserialize-json-that.html
(function () {
'use strict';

angular
    .module('app')
    .factory('jsonPointerParseService', jsonPointerParseService);

jsonPointerParseService.$inject = [];

function jsonPointerParseService() {
    var hashOfObjects = {};

    var service = {
        pointerParse: pointerParse
    };

    return service;

    function collectIds(obj) {
        if (jQuery.type(obj) === "object") {
            if (obj.hasOwnProperty("$id")) {
                hashOfObjects[obj.$id] = obj;
            }
            for (var prop in obj) {
                collectIds(obj[prop]);
            }
        } else if (jQuery.type(obj) === "array") {
            obj.forEach(function (element) {
                collectIds(element);
            });
        }
    }

    function setReferences(obj) {
        if (jQuery.type(obj) === "object") {
            for (var prop in obj) {
                if (jQuery.type(obj[prop]) === "object" &&
                    obj[prop].hasOwnProperty("$ref")) {
                    obj[prop] = hashOfObjects[obj[prop]["$ref"]];
                } else {
                    setReferences(obj[prop]);
                }
            }
        } else if (jQuery.type(obj) === "array") {
            obj.forEach(function (element, index, array) {
                if (jQuery.type(element) === "object" &&
                    element.hasOwnProperty("$ref")) {
                    array[index] = hashOfObjects[element["$ref"]];
                } else {
                    setReferences(element);
                }
            });
        }
    }

    // Set the max depth of your object graph because JSON.stringify will not be able to
    // serialize a large object graph back to
    function setMaxDepth(obj, depth) {
        // If this is not an object or array just return there is no need to
        // set its max depth.
        if (jQuery.type(obj) !== "array" && jQuery.type(obj) !== "object") {
            return obj;
        }

        var newObj = {};

        // If this object was an array we want to return the same type in order
        // to keep this variable's consistency.
        if (jQuery.type(obj) === "array") {
            newObj = [];
        }

        // For each object or array cut off its tree at the depth value by
        // recursively diving into the tree.
        angular.forEach(obj, function (value, key) {
            if (depth == 1) {
                newObj = null;
            }
            else if (jQuery.type(value) === "array") {
                if (setMaxDepth(value, depth - 1)) {
                    newObj[key] = setMaxDepth(value, depth - 1)
                } else {
                    newObj = [];
                }
            } else if (jQuery.type(value) === "object") {
                if (setMaxDepth(value, depth - 1)) {
                    newObj[key] = setMaxDepth(value, depth - 1)
                } else {
                    newObj = [];
                }
            } else {
                newObj[key] = value;
            }
        }, newObj);

        return newObj;
    }

    function pointerParse(obj, depth) {
        var newObj = obj;

        hashOfObjects = {};
        collectIds(newObj);
        setReferences(newObj);

        if (depth) {
            newObj = setMaxDepth(newObj, depth);
        }

        return newObj;
    }
}
})();

Usage would be like so:

 var newObj = jsonPointerParseService.pointerParse(obj);

Please keep in mind, this is an Angular service.  So I inject it into whichever controller needs to have these references resolved, and make the call to pointerParse() accordingly.

Please note though that if you want to post this object back to the server, your browsers JSON.stringify() call has to be able to handle an object with circular references.  By default, in my case, Angular does not call JSON.stringify() with the parameters required to be able to stringify an object with circular references.  So, in this case I would suggest posting only a small portion of data and not this entire object back or instantiating your own call to stringify an object like this.

Lastly, I must say that dealing with $ref is a pain and I decided to preserve reference handling with only arrays.  This seemed to work well for me.  I still had to access array values with $values however I didnt have to worry about resolving references and didnt have to worry about the server blowing up trying to serialize all of the object circular references to json.

json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize;

json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Arrays;

Update: Even with only resolving arrays there are still references that you may need to resolve. In those instances use the pointerParse() function to take care of them.


问:
Tracking hours with clock in/out
I am working on a web interface that would allow the user to keep track of the amount of time people spend at their establishment.

The problem:

I don't know what the best way to keep track of this time would be. I have come up with a couple ideas on how this could be accomplished, but none of them are as elegant as I would like them to be.
I could:

Store clocks in a MySQL database and calculate hours when requested.

Store clocks and hours which would be calculated every time they clock out.

Why these solutions aren't good enough:

Calculating the hours per request would rely heavily on a person clocking in and out in sequence in order to get this done elegantly. This would offer no flexibility when it comes to people forgetting to clock out. Maybe improper clock order could be flagged as a discrepancy and it won't calculate hours until it is resolved? It also seems like the query to get sequential clock ins/outs and determine the difference between them would be cumbersome.

Calculating hours every time a person clocks out seems a little more reasonable, but then you would have to account for people forgetting to clock out. If someone forgets to clock out for a month, they would come back with a bunch of hours and the user would have inaccurate records.

I ask because I may be looking at this problem too closely and am failing to see an obvious solution. Any suggestions?

答:
Your database should be concerned with the facts. The interpretation of the facts does not need to be stored in the database, because it can be calculated on demand, each time you need to display the number of hours between clock-in and clock-out events.

Sure, it might be a bit harder, but trust me, you will have to come up with the algorithm anyway, because at some point the need will arise to recalculate everyone's hours. So, since you will come up with the algorithm, you might as well keep using it each time you need to display hours in the application, instead of each time you perform a clock-out on the database.

Discrepancies in the data due to a person forgetting to clock out is something that you need to handle, either when it is time to show the number of hours, or, better yet, by means of a batch, recurring process which looks for discrepancies and fixes them by inserting extra events to the database.  So, for example, I would run such a process at midnight every day to clock out everyone who apparently forgot to clock out.  (I would also keep track of the fact that this clock-out was system-issued and not user-issued.)

As a bonus, here is a query for Microsoft Access (in MS-SQL Server compatibility mode) that I wrote a long time ago to calculate employee shifts, given clock in and clock out events.  Actions.TypeId=2 means we have a clocked state change, (the system supports other types of events too,) and when that happens, then Actions.Data='0' for a clock-out, while Actions.Data='1' for a clock-in.

```<code>SELECT
    Employees.Id,
    PunchIn,
    (SELECT TOP 1 DateTime FROM Actions
      WHERE EmployeeId = Employees.Id AND TypeId=2 AND Data='0'
        AND DateTime > PunchIn ORDER BY Id)
    AS PunchOut,
    (PunchOut-PunchIn) AS Duration
FROM Employees LEFT JOIN
    (SELECT Actions.EmployeeId, Actions.DateTime AS PunchIn
       FROM Actions
      WHERE Actions.TypeId=2 AND Actions.Data='1')
    AS PunchIns
    ON Employees.Id=PunchIns.EmployeeId
ORDER BY Employees.Id, PunchIn;
</code>```

Title: Tracking hours with clock in/out

Body:
Your database should be concerned with the facts. The interpretation of the facts does not need to be stored in the database, because it can be calculated on demand, each time you need to display the number of hours between clock-in and clock-out events.

Sure, it might be a bit harder, but trust me, you will have to come up with the algorithm anyway, because at some point the need will arise to recalculate everyone's hours. So, since you will come up with the algorithm, you might as well keep using it each time you need to display hours in the application, instead of each time you perform a clock-out on the database.

Discrepancies in the data due to a person forgetting to clock out is something that you need to handle, either when it is time to show the number of hours, or, better yet, by means of a batch, recurring process which looks for discrepancies and fixes them by inserting extra events to the database.  So, for example, I would run such a process at midnight every day to clock out everyone who apparently forgot to clock out.  (I would also keep track of the fact that this clock-out was system-issued and not user-issued.)

As a bonus, here is a query for Microsoft Access (in MS-SQL Server compatibility mode) that I wrote a long time ago to calculate employee shifts, given clock in and clock out events.  Actions.TypeId=2 means we have a clocked state change, (the system supports other types of events too,) and when that happens, then Actions.Data='0' for a clock-out, while Actions.Data='1' for a clock-in.

SELECT
    Employees.Id,
    PunchIn,
    (SELECT TOP 1 DateTime FROM Actions
      WHERE EmployeeId = Employees.Id AND TypeId=2 AND Data='0'
        AND DateTime > PunchIn ORDER BY Id)
    AS PunchOut,
    (PunchOut-PunchIn) AS Duration
FROM Employees LEFT JOIN
    (SELECT Actions.EmployeeId, Actions.DateTime AS PunchIn
       FROM Actions
      WHERE Actions.TypeId=2 AND Actions.Data='1')
    AS PunchIns
    ON Employees.Id=PunchIns.EmployeeId
ORDER BY Employees.Id, PunchIn;


问:
Does context (like as an argument in a function) allow for numbers in code that aren't magic numbers?
I've been reading many of the articles and such about magic numbers, i.e.

wikipedia article

programmers.stackexchange.com article

It seemed like no one has considered context as a means of making it acceptable to use a number and not have it considered magic.

For example

```<code>connection.setLoginTimeoutSeconds(30);
</code>```

Vs

```<code>final int LOGIN_TIMEOUT_30_SECONDS = 30;
connection.setLoginTimeoutSeconds(LOGIN_TIMEOUT_30_SECONDS);
</code>```

or even

```<code>final int LOGIN_TIMEOUT = 30;
connection.setLoginTimeoutSeconds(LOGIN_TIMEOUT);
</code>```

The function name and value has all of the information as the variable name and value:

```<code>setLoginTimeoutSeconds(30);
LOGIN_TIMEOUT_SECONDS = 30;
</code>```

In the case where a variable for the login time out is not needed anywhere else in the code it seems like the first example is more readable and even more maintainable than the latter two and that the number 30 is not magic because of where it resides. Does anyone agree or disagree?

I am not asking about well known constants here like in are-all-magic-numbers-created-the-same. Any constant value can will do. Nor am I asking for my example to be found as flawed because someone could make a problem from it. What I am really asking is form anyone's opinion on if magic number rules need not apply.

答:
Another point not yet mentioned is that there are times when a value ends up getting encoded within the logic of a program in addition to appearing as a literal.  For example, a function to compute the average of three consecutive
values in an array may be written more efficiently and cleanly as

Average = (arr[i-1]+arr[i]+arr[i+1])/3.0; // assume arr is double[]

than using a loop (doing five without a loop would be pushing things, and seven would probably be cleaner with a loop, but for three things the in-line code is simpler).  The 3.0 literal semantically repeats the number of terms being added, which is a slight violation of "Don't Repeat Yourself", but since both usages are close together it will be pretty obvious how they relate.  Making the 3.0 a named constant would make it far less clear that changing the constant would not cause a greater number of terms to be correctly averaged together, but would simply make the computation yield the wrong value.


问:
GPL licensed software in commercial applications
Can I sell a service that is provided using software licensed under GNU GLP?

Additionally, this service involves the use and modification of other modules under Apache and other free software licenses. Is the modification and linking of these softwares allowed, even when the licenses are not compatible? Am I under the obligation to release these modifications or can I maintain them privately and use them only to provide a service, which is sold?

答:
This is three questions: the first regards the use of software; the second is concerned with Apache and other free software licenses; and the third regards having to distribute the software.

Yes, you can use it to provide a service. A Quick Guide to GPLv3 (www.gnu.org/licenses/quick-guide-gplv3.en.html ) says

Nobody should be restricted by the software they use. There are four
  freedoms that every user should have:

the freedom to use the software for any purpose, [...]

for which the most pertinent phrase in the GPL (that I could find at a quick glance, anyway), is

This License explicitly affirms your unlimited permission to run the unmodified Program.

The Apache 2 license is one-way compatible, per www.apache.org/licenses/GPL-compatibility.html

Apache 2 software can [...] be included in GPLv3 projects, because the
  GPLv3 license accepts our software into GPLv3 works. However, GPLv3
  software cannot be included in Apache projects. The licenses are
  incompatible in one direction only, and it is a result of ASF's
  licensing philosophy and the GPLv3 authors' interpretation of
  copyright law.

and other licenses are compatible, per en.wikipedia.org/wiki/GNU_General_Public_License#Compatibility_and_multi-licensing , but it would depend on which other licenses we're talking about.

No, you don't have to distribute it for free, but your customers are at liberty to do so.

If I distribute GPL'd software for a fee, am I required to also make
  it available to the public without a charge?
  (#DoesTheGPLRequireAvailabilityToPublic)

No. However, if someone pays your fee and gets a copy, the GPL gives them the freedom to release it to the public, with or without a
  fee. For example, someone could pay your fee, and then put her copy on
  a web site for the general public.


问:
How to use BPMN and use case and other diagrams together
I asked this question on stackoverflow, but it seems this question is not suitable there, so I post here for discussion.

BPMN (Business Process Modeling Notations) is used for modeling business process by visualization, thus making intangible ideas become physically concrete through the expression of BPMN diagrams. The question is, how do I organize the BPMN with the UML.

Initially, I thought of two ways to organize use cases and business process diagram:

1 to one/many: By mapping each step (step here means each node in the BPMN digram) in the business process diagram with one or several use cases. Each use case is mapped with relevant several class diagrams/component diagrams (I prefer this one, since you can encapsulate a set of classes into one component which has input and output), several sequence diagrams (optional). After you have class diagrams/sequence diagrams, code is written/generated based on the model.

Many to one: By mapping several steps into one use case. The subsequence steps are the same.

Many to many: For example, one step in the business process can be mapped with two or more use cases, and the same two or more use cases can be mapped with other steps.

The above methods can be done by the modeling tool, and in my case, I use Enterprise Architect from Sparx System. I discover it recently and I am using its trial, but I will buy it in the future. I can organize many use case diagrams with one step of the BPMN diagram, and can click to view the necessary use cases. However, I don't if it supports many to many cases.

After thinking my own method for organizing BPMN and Use Cases, I searched the Internet, and found two other papers, each suggest the following method:

Turn each use case into each step of BPMN diagrams: To visualize how refined use cases fit into the business process. I like this approach, since the business process with steps can be modeled, and later each step is turned into a use case. One step is one use case.  This is the same with my one to one mapping above. Original presentation is here: Visualizing Use Case Sets as BPMN Processes

Each use case is exactly a business process: Each step in the use case is each step of the business process. Original paper is here: Describing Business Processes with Use Cases

It seems to me that there's not standardized way of gluing these artifacts (BPMN and Use Cases and other digrams) together. Maybe it's a management problem and rely more on creative usage rather than follow a formal steps. What are the usage of these diagrams together?

答:
I think that this has strayed a bit from what use-cases are.  Remember that use-cases and BPMN are two ways of modeling the same thing, but they are not necessarily meant to be literally translated.  BPMN intends to provide a fully machine executable model. Use-cases to give a natural language explanation for a human.

If we look at the explanation of use-cases (for example in Use-Case Modeling (Bittner et. al.)), they are a dialogue between the system and actors, placing the requirements in context (by providing an example scenario).

This does present the problem that any particular use-case model might not cover the whole of the business, but just a sufficient amount of the business to explain the requirements.

So the closest thing in BPMN is not an activities, but the collaboration and conversations.  The collaboration shows the interaction between pools/participants.  (Check out http://www.omg.org/spec/BPMN/20100601/10-06-02.pdf.)

The BPMN Private/Internal process and activities tell us what the business internally does in response to receiving and input from a participant. It is analogous to building a sequence diagram with the analysis model boundaries, controls, and entities in the unified process.

The BPMN public process http://www.omg.org/spec/BPMN/2.0/PDF/ section 10.1.1.2 shows the use of a activities in an external process, but notes that internal activities are never shown.

In your diagram example, try breaking the Student out into its own participant.  Model the students interaction with the university. Then in a different diagram, model the university's process that realizes each of the public activities.


问:
Iterator pattern - why is it important to not expose the internal representation?
I am reading C# Design Pattern Essentials. I'm currently reading about the iterator pattern.

I fully understand how to implement, but I don't understand the importance or see a use case. In the book an example is given where someone needs to get a list of objects. They could have done this by exposing a public property, such as IList<T> or an Array.

The book writes

The problem with this is that the internal representation in both of these classes has been exposed to outside projects.

What is the internal representation? The fact it's an array or IList<T>? I really don't understand why this is a bad thing for the consumer (the programmer calling this) to know...

The book then says this pattern works by exposing its GetEnumerator function, so we can call GetEnumerator() and expose the 'list' this way.

I assume this patterns has a place (like all) in certain situations, but I fail to see where and when.

答:
A wording I like to use mirrors @CaptainMan 's comment: "It is fine for a consumer to know internal details.  It is bad for a customer to need to know internal details."

If a customer has to type array or IList<T> in their code, when those types were internal details, the consumer must get them right.  If they are wrong, the consumer may not compile, or even get wrong results.  This yields the same behaviors as the other answers of "always hide the implementation details because you shouldn't expose them," but starts to dig at the advantages of not exposing.  If you never expose an implementation detail, your customer can never put themselves in a bind by using it!

I like to think of it in this light because it opens up the concept of hiding the implementation to shades of meaning, rather than a draconian "always hide your implementation details."  There are plenty of situations where exposing implementation is totally valid.  Consider the case of real time device drivers, where the ability to skip past layers of abstraction and poke bytes into the right places can be the difference between making timing or not.  Or consider a development environment where you don't have time to make "good APIs," and need to use things immediately.  Often exposing underlying APIs in such environments can be the difference between making a deadline or not.

However, as you leave those special cases behind and look at the more general cases, it starts to become more and more important to hide implementation.  Exposing implementation details is like rope.  Used properly, you can do all sorts of things with it, like scaling tall mountains.  Used improperly, and it can tie you in a noose.  The less you know about how your product will be used, the more careful you need to be.

The case study that I see time and time again is one where a developer makes an API that isn't very careful about hiding implementation details.  A second developer, using that library, finds that the API is missing some key features they would like.  Rather than writing a feature request (which could have a turnaround time of months), they decide instead to abuse their access to the hidden implementation details (which takes seconds).  This isn't bad in and of itself, but often the API developer never planned on that being part of the API.  Later, when they improve the API and change that underlying detail, they find they are chained to the old implementation, because someone used it as part of the API.  The worst version of this is where someone used your API to provide a customer-centric feature, and now your company's paycheck is tied to this flawed API!  Simply by exposing implementation details when you did not know enough about your customers proved to be enough rope to tie a noose around your API!


问:
Should I always return an error code from C functions?
I have the following code in many places in a large application:

```<code>if (datastruct.data_ok &&
    cur_time > datastruct.start_time && cur_time < datastruct.end_time)
{
  do_something();
}
</code>```

Now, I wanted to eliminate repeated code by defining a function time_ok(...) which would simplify the repeated code to:

```<code>if (time_ok(&datastruct, cur_time))
{
  do_something();
}
</code>```

In my opinion, this is a well-made refactoring and should be therefore done. If the definition of the condition changes in the future, code maintenance becomes easier as only one location needs to be changed.

However, several team members noticed that the function can be abused by giving it a NULL argument, which crashes the program. They also complained that the return value is a boolean and not an error code, and all functions should according to them return an error code.

So, he refactoring would according to them be done in the following way:

```<code>bool time_ok_condition;
int err;
err = time_ok(&datastruct, &time_ok_condition, cur_time);
if (err != 0)
{
  fprintf(stderr, "Error %d at file %s line %d", err, __FILE__, __LINE__);
  exit(1);
}
if (time_ok_condition)
{
  do_something();
}
</code>```

However, in my opinion this results in excessively long code and if I really
have to do all this, I'd much rather have the original non-refactored code.

I invented a way around this rule by using a macro:

```<code>if (TIME_OK(datastruct, cur_time))
{
  do_something();
}
</code>```

...which can never crash the program on NULL arguments as the macro takes the structure name and not a pointer to the structure as the argument. However, I don't particularly like this approach of using a macro because the macro evaluates its arguments multiple times.

I noticed that although C was developed for Unix and Unix system calls traditionally return error codes, the standard C library functions such as strstr, strchr, strspn do not return an error code and therefore handle NULL arguments by crashing the program.

Now, it is an entirely different question whether the program should crash with coredump or print a meaningful error message for the theoretical error that never happens in this program (see the question How should “this can never happen” style of errors in C be handled? on Stack Overflow).

However, this question is about whether it should be allowed to return something else than an error code. A positive answer would in practice necessitate the use of "crash with coredump" strategy in this very specific case as the range of a boolean return cannot represent errors, but does not necessarily mean that a "crash with coredump" strategy is optimal in all cases.

Who is correct? Should C functions always return an error code like Unix system calls, or should it be allowed to write functions that return something else if there is justified reason for it such as code simplicity?

答:
All functions should return an error code?

I can't see a good reason change a function like

```<code>int Add( int lhs, int rhs ) {...}
</code>```

to

```<code>// Out parameter: result
error_t Add( int lhs, int rhs, int * result ) {...}
</code>```

especially as now you are having to deal with the possibility that result is null.

In your specific example, I would use something similar to the first form without the pointer, leaving to the compiler the decision between inlining to save the copying vs the increase in code size (for something this small I expect it to always pick inlining, but it is in a better position to judge)

```<code>bool time_ok( data_t datastruct, time_t cur_time ) {
    return datastruct.data_ok &&
           ( cur_time > datastruct.start_time ) &&
           ( cur_time < datastruct.end_time )
}
</code>```

where data_t and time_t are the types of datastruct and cur_time

This relies on the fact that time_ok is a Total Function (i.e. not a Partial Function), equivalently that for all data_t and for all time_t there is a defined bool that time_ok can return. This is easiest to prove in cases such as this, where the only thing occurring is values are compared and combined.

Body:
All functions should return an error code?

I can't see a good reason change a function like

int Add( int lhs, int rhs ) {...}

to

// Out parameter: result
error_t Add( int lhs, int rhs, int * result ) {...}

especially as now you are having to deal with the possibility that result is null.

In your specific example, I would use something similar to the first form without the pointer, leaving to the compiler the decision between inlining to save the copying vs the increase in code size (for something this small I expect it to always pick inlining, but it is in a better position to judge)

bool time_ok( data_t datastruct, time_t cur_time ) {
    return datastruct.data_ok &&
           ( cur_time > datastruct.start_time ) &&
           ( cur_time < datastruct.end_time )
}

where data_t and time_t are the types of datastruct and cur_time

This relies on the fact that time_ok is a Total Function (i.e. not a Partial Function), equivalently that for all data_t and for all time_t there is a defined bool that time_ok can return. This is easiest to prove in cases such as this, where the only thing occurring is values are compared and combined.


问:
Why would you not use the 'using' directive in C#?
The existing coding standards on a large C# project includes a rule that all type names be fully qualified, forbidding employment of the 'using' directive. So, rather than the familiar:

```<code>using System.Collections.Generic;

.... other stuff ....

List<string> myList = new List<string>();
</code>```

(It's probably no surprise that var also is prohibited.)

I end up with:

```<code>System.Collections.Generic.List<string> myList = new System.Collections.Generic.List<string>();
</code>```

That's a 134% increase in typing, with none of that increase providing useful information. In my view, 100% of the increase is noise (clutter) that actually impedes understanding.

In 30+ years of programming, I've seen such a standard proposed once or twice, but never implemented. The rationale behind it escapes me. The person imposing the standard is not stupid, and I don't think he's malicious. Which leaves misguided as the only other alternative unless I'm missing something.

Have you ever heard of such a standard being imposed? If so, what was the reason behind it? Can you think of arguments other than "it's stupid," or "everybody else employs using" that might convince this person to remove this prohibition?

Reasoning

The reasons for this prohibition were:

It's cumbersome to hover the mouse over the name to get the fully qualified type. It's better to always have the fully qualified type visible all the time.

Emailed code snippets don't have the fully qualified name, and therefore can be difficult to understand.

When viewing or editing the code outside of Visual Studio (Notepad++, for example), it's impossible to get the fully qualified type name.

My contention is that all three cases are rare, and that making everybody pay the price of cluttered and less-understandable code just to accommodate a few rare cases is misguided.

Potential namespace conflict issues, which I expected to be the primary concern, weren't even mentioned. That's especially surprising because we have a namespace, MyCompany.MyProject.Core, which is an especially bad idea. I learned long ago that naming anything System or Core in C# is a quick path to insanity.

As others have pointed out, namespace conflicts are easily handled by refactoring, namespace aliases, or partial qualification.

答:
The problem with using is that it magically adds to the namespace without an explicit declaration.  This is much more of a problem for the maintenance programmer who encounters something like List<> and without being familiar with the domain, does not know which using clause has introduced it.

A similar problem occurs in Java if one writes import Java.util.*; rather than import Java.util.List; for example;  the latter declaration documents what name has been introduced so that when List<> occurs later in the source, its origin is known from the import declaration.


问:
In which layer I should implement file parsing?
in a simple multi layer architecture, in which layer do I have to implement something like parsing file.
For example: I have a file and I have to extract specific information into an object.
I think that this stuff is data access, because the business layer need data. How and where the data come from is not the point. do you agree? </p>

答:
In parsing data from a file, you can do that in UserServicesLayer, if you are going to manipulate those data that needs any logical condition, it is the time to call the BusinessLayer then do all logical things inside that layer, your DataAccessLayer is like your bridge to access the data from database, therefore it is not advisable to do the extraction of data inside the DataAccesLayer.

Hope this helps.


问:
What are R-value references used for?
I'm trying to dig deep into C++ and really learn the nuances of the language but one thing I've found to be really confusing is the R-Value reference. The whole double ampersand thing to be clear (in case I'm getting the terminology wrong). It's not a big deal as it doesn't seem to come up often but it seems like it could occasionally be useful to know.</p>

答:
lvalue : A value that resides in memory (heap or stack) and addressable.

rvalue : A value that's not lvalue.

It resides only on the right side of an assignment expression such as a literal or a temporary which is intended to be non-modifiable.

here is very good tutorial about it:

http://www.bogotobogo.com/cplusplus/C11/4_C11_Rvalue_Lvalue.php

Title: What are R-value references used for?


答:
A common use case is the “move constructor,” invoked when an object is being copied from a temporary that’s about to expire (a rvalue).  An example is foo = bar + baz; where bar + baz is a temporary on the right-hand side of an assignment statement.

Before rvalue references, objects that made deep copies of their contents had to construct their data in one place, then copy it all to another, then destroy the first copy.  This was slow and wasteful.

When the source is a rvalue reference, the move constructor or assignment operator will typically make a shallow copy of the source’s data, then remove the source’s references so that it will be an empty shell when it’s deleted a moment later and the data will now have a new owner.  This is safe, because a rvalue reference won’t be used for anything else before it’s destroyed, much faster, and saves memory.

Title: What are R-value references used for?

Body: I'm trying to dig deep into C++ and really learn the nuances of the language but one thing I've found to be really confusing is the R-Value reference. The whole double ampersand thing to be clear (in case I'm getting the terminology wrong). It's not a big deal as it doesn't seem to come up often but it seems like it could occasionally be useful to know.</p>


答:
In most multi-layer architectures, the Data Access Layer (DAL) is reserved for transporting data to and from the primary backing storage of the application (usually a database).

For other kinds of data access (data exchange with third parties, reading/writing files, etc.) those architectures have the concept of Services to perform the transportation of the data and to transform it between the external format and something that the business layer can work with.

So, in your architecture, the file reading and parsing would go in a Service, usually named after the kind of file or data it processes. For example a XMLImportService.

Title: In which layer I should implement file parsing?

Body:
in a simple multi layer architecture, in which layer do I have to implement something like parsing file.
For example: I have a file and I have to extract specific information into an object.
I think that this stuff is data access, because the business layer need data. How and where the data come from is not the point. do you agree? </p>


问:
Why does this evaluation function work in a connect four game in java
I am exploring how a Minimax algorithm can be used in a connect four game.  I was looking through a program and found this evaluation function.

```<code>private static int[][] evaluationTable = {{3, 4, 5, 7, 5, 4, 3},
                                          {4, 6, 8, 10, 8, 6, 4},
                                          {5, 8, 11, 13, 11, 8, 5},
                                          {5, 8, 11, 13, 11, 8, 5},
                                          {4, 6, 8, 10, 8, 6, 4},
                                          {3, 4, 5, 7, 5, 4, 3}};

//here is where the evaluation table is called
public int evaluateContent() {
        int utility = 128;
        int sum = 0;
        for (int i = 0; i < rows; i++)
            for (int j = 0; j <columns; j++)
                if (board[i][j] == 'O')
                    sum += evaluationTable[i][j];
                else if (board[i][j] == 'X')
                    sum -= evaluationTable[i][j];
        return utility + sum;
    }
</code>```

And then a MiniMax algo is used to evaluate the possible solutions.

I am not sure how/why this works.  Would anyone be able to explain?

答:
This evaluation function is nothing but Gaussian normal distribution centered around the mean position of board. The one with more centered positions gets higher score from this eval func. If you plot this matrix in MATLAB, you'll find that the values form a tent and hence give bias to center position. However I must say there are way better evaluation function than this as this performs total evaluation and doesn't do spatial analysis.

```<code>score = board.longest_chain(board.get_current_player_id()) * 10
        # Prefer having your pieces in the center of the board.
        # score boost
        for row in range(6):
            for col in range(7):
                if board.get_cell(row, col) == board.get_current_player_id():
                    score -= abs(3-col)
                elif board.get_cell(row, col) == board.get_other_player_id():
                    score += abs(3-col)
</code>```

Above is just one example where it applies center oriented idea over spatial analysis result obtained via longest_chain.

Body:
This evaluation function is nothing but Gaussian normal distribution centered around the mean position of board. The one with more centered positions gets higher score from this eval func. If you plot this matrix in MATLAB, you'll find that the values form a tent and hence give bias to center position. However I must say there are way better evaluation function than this as this performs total evaluation and doesn't do spatial analysis.

score = board.longest_chain(board.get_current_player_id()) * 10
        # Prefer having your pieces in the center of the board.
        # score boost
        for row in range(6):
            for col in range(7):
                if board.get_cell(row, col) == board.get_current_player_id():
                    score -= abs(3-col)
                elif board.get_cell(row, col) == board.get_other_player_id():
                    score += abs(3-col)

Above is just one example where it applies center oriented idea over spatial analysis result obtained via longest_chain.


问:
What does k stand for in gitk?
I wonder k must mean something in gitk. Could not find it on Google.

Found that git was named by Linus Torvalds out of imagination. But when a tool was added with name gitk, there must be something in their mind.

https://www.quora.com/Why-is-Git-called-Git

答: Gitk is built on top of a GUI library named "Tk", a graphical toolkit originally designed for the Tcl language.  "Gitk" is a combination of "Git" + "Tk" and then they removed the extra "t" in the middle. Thus, "k" literally stands for "kit".

Title: What does k stand for in gitk?


答:
I think that this stuff is data access, because the business layer
  need data. How and where the data come from is not the point. Are your
  agree?

I'm splitting such things into two layers actually.

Generic file parsing routines (GenericCSVParser for example) go to Infrastructure layer because they have nothing to do with business logic of the application. It's just a file parsing tool which might be a part of the framework itself.

Specialized file parsers (InvoiceCSVFileParser for example) usually compose or inherit from generic ones and they belong to business logic layer.


答:
I would recommend to stop thinking in terms of "layers" and start thinking in terms of "modules". Right now, your Data Access layer contains only Database access module. So right next to it, you would put File Access module. This module would be in same layer as Database access module in terms of which modules it can reference and which modules can reference it. But it would probably be separate library, just like Database access module is it's own library (or I strongly hope so).

Even better case would be if you had an abstraction for saving and loading business data. The Data access layer (and its including modules) would then contain implementations of this abstraction. So you would have SaveDataInDatabase, SaveDataInFileX and SaveDataInFileY classes. The business code would then use this abstraction without knowing or caring how the data will be persisted.


问:
Real world pitfalls of introducing F# into a large codebase and engineering team
I'm CTO of a software firm with a large existing codebase (all C#) and a sizable engineering team.  I can see how certain parts of the code would be far easier to write in F#, resulting in faster development time, fewer bugs, easier parallel implementations, etc., basically overall productivity gains for my team.  However, I can also see several productivity pitfalls of introducing F#, namely:

1) Everyone has to learn F#, and it's not as trivial as switching from, say, Java to C#.  Team members that have not learned F# will be unable to work on F# parts of the codebase.

2) The pool of hireable F# programmers, as of now (Dec 2010) is non-existent.  Search various software engineer resume databases for "F#", way less than 1% of resumes contain the keyword.

3) Community support as of now (Dec 2010) is less available.  You can google almost any problem in C# and find someone that has already dealt with it, not so with F#.  Third party tool support (NUnit, Resharper etc) is also sketchy.

I realize that this is a bit Catch-22, i.e. if people like me don't use F# then the community and tools will never materialize, etc.  But, I've got a company to run, and I can be cutting edge but not bleeding edge.

Any other pitfalls I'm not considering?  Or anyone care to rebut the pitfalls I've mentioned?  I think this is an important discussion and would love to hear your counter-arguments in this public forum that may do a lot to increase F# adoption by industry.

答:
I've contemplated this exact situation.

This is what I plan for my team:

Mix C# with F#, this can be done by using C# for the majority of the code-base. Where heavy data processing is required, write the associated functions in F# and put it inside a dll, or reference it. Example here

Slowly re-factor your existing code-base in the above fashion.

Not all code has to be functional.

Get your team to learn the basics of Haskell, LISP over the weekends.

Get them to learn F#, by trying to solve Euler Project puzzles (that helped me a lot when I was learning F#). Again this should be something done say over the week end, or during work time if you want set a day aside for "training".

OwnerDisplayName: nganju

ContentLicense: CC BY-SA 2.5


问:
Best pattern to write a PHP function that checks on access and returns more then boolean?
I'm prototyping behaviour of a new application, and want to write some functions that check on access based on some variable dates.

I just want to write separate functions for that, like "canUserSeeThis()" and "canUserSeeThat()"

In case one of these returns false, I want to display a message, but I want that message to be defined in these functions, but the rendering taking part outside the functions.

What is the best "pattern" to quickly build such a functionality? Should I let the message be in the return value? Should I work with throwing exceptions?

I'm just prototyping, so I don't want to end up defining a complete API system yet.

答:
In case one of these returns false, I want to display a message, but I
  want that message to be defined in these functions, but the rendering
  taking part outside the functions.

I think this is a bad idea. In my application permission checking is done using lightweight Acl objects. They contain boolean methods checking for permissions. And this is businesss logic layer.

Message display is done in the UI layer and it is dangerous to mix them up.


问:
What does the prefix "on" in a function (e.g."onButtonPressed") mean?
Sometimes I'll see some functions use "on" as a prefix, for example, on a button listener:

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

and there are other examples:

```<code>onStateChanged();
onNotified();
onResume();
</code>```

Does the prefix "on" have an implied semantic meaning behind it?

答:
"OnXXX" is typically something with events, but different platforms have different naming conventions, so the exact role depends on the language, which can get confusing.

In .net UI classes, a method name with the prefix "On" is a method which causes an event to be fired. For example, Button.OnClick() is the method which fires the Click-event. The OnXXX methods are protected, so it is only the object itself which can fire the events. This pattern holds for both web forms, windows forms and WPF.

But in asp.net web control markup, the attributes named OnXXX has a different meaning since they registers an event handler for the event. Eg. OnClick="Btn1_Click" registers the method Btn1_Click as a handler for the Click event. In other words the OnClick attribute on a web control does not correspond directly to the OnClick method. Rather it corresponds to the code Click += Btn1_Click. Honestly, this is somewhat confusing, and in XAML-markup the convention is changed, so the name of the attributes which attach events does not have the "On"-prefix but match the name of the event directly, eg.: Click="Btn1_Click".

In JavaScript, the conventions are different. Here onXXX is the name of an event handler. Eg. button.onclick is a method which is called when the click event is fired (rather then a method which fires the event as in .net). The eventhandler atttributes in html are also named onXXX and attaches an eventhandler, eg. onclick="handleClick()" registers a handler for the click event (as in Asp.net).


问:
Single responsibility policy problem
I'm a bit stuck using the single responsibility policy.

I have a class named Parser, which can be configured to parse input a certain way. For the sake of convenience I will limit the configuration properties to a single property config in the following example:

```<code>class Parser {

    boolean config;
    State state;

    AST parse(String input) { ... }
}
</code>```

I want to reuse the parse instance for multiple parses. The problem is that the state is redundant for the instance itself, however it is required while parsing. Beside the overhead of the state in memory, it doesn't work in multi-threaded environment.

The same goes for a class named Compiler:

```<code>class Compiler {

    boolean config;
    State state;

    Code compile(String input) { ... }
}
</code>```

I was wondering how this is generally solved.

Note: This is maybe a minimal example, but I'm often stuck thinking of a better design.

答:
If your State is needed only by parse() method, why do you keep it in the instance? Why not to create State objects only when they are really needed? You could then pass them around to the methods, called by parse() if needed.

If most methods inside Parser use State, then you should just not reuse the instance. Object construction is usually very cheap if you keep your constructors lightweight. If configuration of the Parser is complex, use factories to construct them. Use Flyweights if configuration process itself is time-consuming.

If you can avoid using single object from different threads - please do so at all costs. The less synchronization problems you have the better, believe me.

Title: Single responsibility policy problem


答:
I once faced a similar problem. While my solution certainly is not optimal, it did the trick.

I used an additional layer between the actual compiling and the concurrently used Compiler-class. This class would be called Compilation in your example.

```<code>/*
 This class exists once for multiple (simultaneous) inputs
*/
public class Compiler{
    CompilationParameters compilationParameters;

    public Compiler(CompilationParameters params){
        ...
    }

    public CompilationResult compile(CompilationInput input){           // Of course you can simplify this to a string

        Compilation compilation = new Compilation(compilationParameters, input);
        compilation.compile();
        return compilation.getResult();
    }
}

/*
 This class exists exactly once per input
*/
public class Compilation{
    CompilationState state;

    public Compiler(CompilationParameters params, CompilationInput input){
        ...
    }
    public void compile(){
        ...
    }
    public CompilationResult getResult(){
        ...
    }
}
</code>```

Now you could argue, that this violates the Open-Closed-Principle. And you'd be right. This solution can be extended for different types of compilations using a factory-pattern for the creation of the Compilation-object. Imagine the following:

```<code>public abstract class Compilation{...};
public class CompiletimeOptimizedCompilation extends Compilation{...};
public class RuntimeOptimizedCompilation extends Compilation{...};
public class CompilationFactory{
    public static Compilation createCompilation(CompilationType type, CompilationParameters params, CompilationInput input)
    {
        switch(CompilationType)
        {
        case eCompileTimeOptimized:
            return new CompileTimeOptimizedCompilation(params, input);
        case eRuntimeOptimized:
            return new RuntimeOptimizedCompilation(params, input);
        case ...
        }
    }
}
</code>```

In this case Compilation might also be an interface instead of an abstract class. To decide that I'd probably need more details about the implementations. And of course the Compiler-class would boil down to:

```<code>public class Compiler{
    CompilationParameters compilationParameters;

    public Compiler(CompilationType type, CompilationParameters params){ // This type CAN be part of the parameters
        ...
    }

    public CompilationResult compile(CompilationInput input){           // Of course you can simplify this to a string

        Compilation compilation = CompilationFactory.createCompilation(type, compilationParameters, input);
        compilation.compile();
        return compilation.getResult();
    }
}
</code>```

Of course the same works for your Parser-class, but I thought it would be a bad example because the noun of "to parse" is "the parse".

If you have any further questions or remarks, don't hesitate asking.

PS: Please excuse any spelling mistakes. I'm not a native.

Title: Single responsibility policy problem

Body:
I'm a bit stuck using the single responsibility policy.

I have a class named Parser, which can be configured to parse input a certain way. For the sake of convenience I will limit the configuration properties to a single property config in the following example:

```<code>class Parser {

    boolean config;
    State state;

    AST parse(String input) { ... }
}
</code>```

I want to reuse the parse instance for multiple parses. The problem is that the state is redundant for the instance itself, however it is required while parsing. Beside the overhead of the state in memory, it doesn't work in multi-threaded environment.

The same goes for a class named Compiler:

```<code>class Compiler {

    boolean config;
    State state;

    Code compile(String input) { ... }
}
</code>```

I was wondering how this is generally solved.

Note: This is maybe a minimal example, but I'm often stuck thinking of a better design.

Body:
I once faced a similar problem. While my solution certainly is not optimal, it did the trick.

I used an additional layer between the actual compiling and the concurrently used Compiler-class. This class would be called Compilation in your example.

/*
 This class exists once for multiple (simultaneous) inputs
*/
public class Compiler{
    CompilationParameters compilationParameters;

    public Compiler(CompilationParameters params){
        ...
    }

    public CompilationResult compile(CompilationInput input){           // Of course you can simplify this to a string

        Compilation compilation = new Compilation(compilationParameters, input);
        compilation.compile();
        return compilation.getResult();
    }
}

/*
 This class exists exactly once per input
*/
public class Compilation{
    CompilationState state;

    public Compiler(CompilationParameters params, CompilationInput input){
        ...
    }
    public void compile(){
        ...
    }
    public CompilationResult getResult(){
        ...
    }
}

Now you could argue, that this violates the Open-Closed-Principle. And you'd be right. This solution can be extended for different types of compilations using a factory-pattern for the creation of the Compilation-object. Imagine the following:

public abstract class Compilation{...};
public class CompiletimeOptimizedCompilation extends Compilation{...};
public class RuntimeOptimizedCompilation extends Compilation{...};
public class CompilationFactory{
    public static Compilation createCompilation(CompilationType type, CompilationParameters params, CompilationInput input)
    {
        switch(CompilationType)
        {
        case eCompileTimeOptimized:
            return new CompileTimeOptimizedCompilation(params, input);
        case eRuntimeOptimized:
            return new RuntimeOptimizedCompilation(params, input);
        case ...
        }
    }
}

In this case Compilation might also be an interface instead of an abstract class. To decide that I'd probably need more details about the implementations. And of course the Compiler-class would boil down to:

public class Compiler{
    CompilationParameters compilationParameters;

    public Compiler(CompilationType type, CompilationParameters params){ // This type CAN be part of the parameters
        ...
    }

    public CompilationResult compile(CompilationInput input){           // Of course you can simplify this to a string

        Compilation compilation = CompilationFactory.createCompilation(type, compilationParameters, input);
        compilation.compile();
        return compilation.getResult();
    }
}

Of course the same works for your Parser-class, but I thought it would be a bad example because the noun of "to parse" is "the parse".

If you have any further questions or remarks, don't hesitate asking.

PS: Please excuse any spelling mistakes. I'm not a native.


问:
When to use Constructor and when to use Collection Initializer?
I am having a .Net class which has 10 properties like given below: [the datatypes of individual property is just a placeholder here and it can be anything from a primitive type to an object to a list of objects]

```<code>class MyClass
{
   internal int Property1{Get;Set;}
   internal string Property2{Get;Set;}
   internal Myclass2 Property3{Get;Set;}
   internal MyAnotherClass Property4{Get;Set;}
   internal int Property5{Get;Set;}
   internal int Property6{Get;Set;}
   internal List<string> Property7{Get;Set;}
   internal int Property8{Get;Set;}
   internal MyThirdClass Property9{Get;Set;}
   internal int Property10{Get;Set;}
}
</code>```

The purpose of this class is to just hold data and this class will not have any function behavior [similar to POCO classes]. Now I am trying to understand here, as should I create a parameterized constructor in the class and pass it all the values to set these properties or should I use the Collection Initializer to set these properties.

In all cases, all the properties would be set so there is no question of setting selective properties.

If I go ahead with the approach of using constructor then I would create the private members for each of these properties and use them inside the constructor to assign it the respective values. This will avoid calling 10 Setter methods just to create one object of MyClass, but will result in creating a constructor which takes 10 parameters.

Is there a documentation which explains in which case one is advised to use constructor instead of Collection Initializer and Vise a versa? I personally prefer creation of Constructor.

答:
From what you've described, it sounds like it would make more sense to have a constructor with 10 parameters and make the property setters private.

Within the constructor, you would then assign the properties from the parameters.

A discussion which runs and runs is whether you should set the member variable directly in the setter rather than use a property. Yes, there is a minimal performance hit but IMHO that is syntactically preferable to referring to the property storage directly in the constructor and the property elsewhere.

As for when you'd use constructors or properties, that depends on the design. If there are known collections of properties you'd wish to set up, then you may wish to create a number of constructors. Alternatively, you may just wish to allow an empty constructor and have the user set any properties they wish. Clearly the constructor gives more control as some properties may have certain business rules. Ultimately, it is a design decision - there are no real rules of thumb to apply here.


答:
Since it is an internal class, there is no benefit to using read/write automatic properties; you are creating lots of get/set methods in your resultant IL.

Assuming you are using C# 6, you have two options:

1 Make the class invariant:

```<code>internal class MyClass
{
    internal MyClass(int property1, int property2, int property3, int property4, int property5,
                     int property6, int property7, int property8, int property9, int property10)
    {
        Property1 = property1;
        Property2 = property2;
        Property3 = property3;
        Property4 = property4;
        Property5 = property5;
        Property6 = property6;
        Property7 = property7;
        Property8 = property8;
        Property9 = property9;
        Property10 = property10;
    }

    internal int Property1 { get; }
    internal int Property2 { get; }
    internal int Property3 { get; }
    internal int Property4 { get; }
    internal int Property5 { get; }
    internal int Property6 { get; }
    internal int Property7 { get; }
    internal int Property8 { get; }
    internal int Property9 { get; }
    internal int Property10 { get; }
}
</code>```

The disadvantage to this approach is that you now have a constructor with ten parameters, which is a definite code smell and cumbersome to use.

2 Use fields and initialise the class via an object initializer:

```<code>internal class MyClass
{
    internal int Property1;
    internal int Property2;
    internal int Property3;
    internal int Property4;
    internal int Property5;
    internal int Property6;
    internal int Property7;
    internal int Property8;
    internal int Property9;
    internal int Property10;
}

...

var x = new MyClass
{
    Property1 = 1,
    Property2 = 1,
    Property3 = 1,
    Property4 = 1,
    Property5 = 1,
    Property6 = 1,
    Property7 = 1,
    Property8 = 1,
    Property9 = 1,
    Property10 = 1,
};
</code>```

The disadvantage to this approach is that you now have a mutable data object, which is unlikely to be what you want.

One way to get around this is to refactor the class into a number of separate classes, each with 3-4 values. Whether this is practical or desirable in your case is difficult to tell as your example lacks any information on what the real values are.

Title: When to use Constructor and when to use Collection Initializer?

Body:
I am having a .Net class which has 10 properties like given below: [the datatypes of individual property is just a placeholder here and it can be anything from a primitive type to an object to a list of objects]

```<code>class MyClass
{
   internal int Property1{Get;Set;}
   internal string Property2{Get;Set;}
   internal Myclass2 Property3{Get;Set;}
   internal MyAnotherClass Property4{Get;Set;}
   internal int Property5{Get;Set;}
   internal int Property6{Get;Set;}
   internal List<string> Property7{Get;Set;}
   internal int Property8{Get;Set;}
   internal MyThirdClass Property9{Get;Set;}
   internal int Property10{Get;Set;}
}
</code>```

The purpose of this class is to just hold data and this class will not have any function behavior [similar to POCO classes]. Now I am trying to understand here, as should I create a parameterized constructor in the class and pass it all the values to set these properties or should I use the Collection Initializer to set these properties.

In all cases, all the properties would be set so there is no question of setting selective properties.

If I go ahead with the approach of using constructor then I would create the private members for each of these properties and use them inside the constructor to assign it the respective values. This will avoid calling 10 Setter methods just to create one object of MyClass, but will result in creating a constructor which takes 10 parameters.

Is there a documentation which explains in which case one is advised to use constructor instead of Collection Initializer and Vise a versa? I personally prefer creation of Constructor.

Body:
Since it is an internal class, there is no benefit to using read/write automatic properties; you are creating lots of get/set methods in your resultant IL.

Assuming you are using C# 6, you have two options:

1 Make the class invariant:

internal class MyClass
{
    internal MyClass(int property1, int property2, int property3, int property4, int property5,
                     int property6, int property7, int property8, int property9, int property10)
    {
        Property1 = property1;
        Property2 = property2;
        Property3 = property3;
        Property4 = property4;
        Property5 = property5;
        Property6 = property6;
        Property7 = property7;
        Property8 = property8;
        Property9 = property9;
        Property10 = property10;
    }

    internal int Property1 { get; }
    internal int Property2 { get; }
    internal int Property3 { get; }
    internal int Property4 { get; }
    internal int Property5 { get; }
    internal int Property6 { get; }
    internal int Property7 { get; }
    internal int Property8 { get; }
    internal int Property9 { get; }
    internal int Property10 { get; }
}

The disadvantage to this approach is that you now have a constructor with ten parameters, which is a definite code smell and cumbersome to use.

2 Use fields and initialise the class via an object initializer:

internal class MyClass
{
    internal int Property1;
    internal int Property2;
    internal int Property3;
    internal int Property4;
    internal int Property5;
    internal int Property6;
    internal int Property7;
    internal int Property8;
    internal int Property9;
    internal int Property10;
}

...

var x = new MyClass
{
    Property1 = 1,
    Property2 = 1,
    Property3 = 1,
    Property4 = 1,
    Property5 = 1,
    Property6 = 1,
    Property7 = 1,
    Property8 = 1,
    Property9 = 1,
    Property10 = 1,
};

The disadvantage to this approach is that you now have a mutable data object, which is unlikely to be what you want.

One way to get around this is to refactor the class into a number of separate classes, each with 3-4 values. Whether this is practical or desirable in your case is difficult to tell as your example lacks any information on what the real values are.


问:
Is MVC now the only way to write PHP?
Hey... its XMAS Eve and something is bugging me... yes, I have work on my mind even when I am on holiday. The vast amount of frameworks available for PHP now use MVC. Even ASP.net has its own MVC module.

I can see the attraction of MVC, I really can and I use it frequently. The only downside that I can see is that you have to fire up the whole system to execute a page request. Depending on your task this can be a little wasteful.

So the question. In a professional environment is this the only way to use PHP nowadays or are their other design methods which have alternative benefits?

答: MVC is usually the most natural way of separating concerns in medium to large web applications. Nobody says you have to do it that way. If your domain suggests another way of separating the application into manageable pieces then you should do it that way. Chances are high though that you'll settle on a variation of the MVC pattern if you separate the application logic properly.</p>

Title: Is MVC now the only way to write PHP?


问:
Call by value for classes c++ design decision
I wonder why C++ uses 'call by value' for classes as default? I imagine this could have advantages in the sense of performance (speed). I mean C# and Java pass classes as references as default.

What are the reasons why C++ pass classes as copies as default?

答:
For C++, the answer is simple: Classes are structs (or the other way round), and structs are passed by value because they are passed by value in C. This ensures that a usable subset of C can be compiled as C++ code.

For C, it's not that straight-forward. But C has the unique feature that it does not have implicit references. Anything that would use an implicit reference in other languages uses an explicit pointer in C. (The only implicit thing about pointers in C is the implicit decay of arrays and function names to pointers.)

This explicit-pointer feature has two beneficial effects:

It helps to keep the language simple.

If you have implicit references, you have at the very least to differentiate between the creation of a reference and an assignment of the data behind that reference, like C++ does. Or you have to make the objects themselves unassignable like Java does. Or you have to have special syntax to assign the reference like Fortran does.

Either way adds significant complexity to the language and the compiler on top of the explicit pointer scheme. Yet, those explicit pointers allow you to do anything other languages do with implicit references by just adding an occasional * or &, or swapping a -> for a ..

It eases reasoning about what memory a function call can touch. When you see a call like foo(myStruct), you know that foo() cannot change myStruct without even looking at the declaration of foo(). On the other hand, foo(&myStruct) gives a strong signal that myStruct will not be the same after the call.

I consider C++ references as a step back in this regard.

On the performance consideration: It is impossible to say that either pass-by-value or pass-by-reference is faster in general. The truth is, that pass-by-value is faster for simple types, and pass-by-reference is faster for complex types.

The designers of C must have known that most structs would be faster with pass-by-reference. I believe that they went for an all-pass-by-value language anyway because they felt that passing implicit references is detrimental to language simplicity with doubtful effects on its usability.


答:
You are labouring under a misconception:

Java and C are always pass-by-value, C# and C++ only by default.

(C# has out and ref arguments, C++ has references.)

The difference between C++ and Java/C# is that in the latter two you can only ever get a pointer (called reference) to a class-type (or any other so-called reference-type, and only to those).

And why is it the default respective only way by value?

Consistency, safety and simplicity. It's the simplest way and reduces unintended modification of the arguments.

Anyway, it's as easy to emulate pass-by-reference (or add syntax to do it) starting from that point, as it is to emulate pass-by-value the other way around.

Title: Call by value for classes c++ design decision

Body:
I wonder why C++ uses 'call by value' for classes as default? I imagine this could have advantages in the sense of performance (speed). I mean C# and Java pass classes as references as default.

What are the reasons why C++ pass classes as copies as default?


问:
Should UDP data payloads include a CRC?
For a company I used to work for, I had to implement a socket receiver that mostly took data in UDP form over a local connection from some specialized sensor hardware. The data in question was a well-formed UDP packet, but interestingly, the data payload always ended with a CRC16 checksum formed using the rest of the data.

I implemented the check on my end, as per the spec, but I always wondered if this was necessary. After all, doesn't the UDP protocol itself carry a 16-bit CRC? Therefore, although UDP packets can be lost or out-of-order, I was under the impression that they can not be corrupted without being discarded by the network hardware before they reach the OS's processes. Or is there some special use-case I'm missing?

It's worth adding that I was working in the defence industry, which as I'm sure you can imagine, likes to be super-explicit about everything like this, so I'm wondering whether it was just a case of "security OCD"...

答:
The UDP protocol does not guarantee that messages are delivered in order or delivered at all, but it does ensure that those messages which do get delivered are complete and unchanged by automatically including a 16-bit checksum. That means adding another 16-bit checksum on the application layer is usually redundant.

...usually....

First, with IPv4 (not IPv6), the checksum is optional. That means you might be using an exotic configuration which doesn't do checksum generation and validation (but in that case you should rather fix your network stack instead of jury-rigging this on the application layer).

Second, with a 16bit checksum there is a one in 65536 chance that a completely random message happens to have a valid checksum. When this margin of error is too large for your use-case (and in the defense industry I could imagine several where it is), adding another CRC-16 checksum would further reduce it. But in that case you might consider to use a proper message digest like SHA-256 instead of CRC-16. Or go all the way and use a real cryptographic signature. This protects not just against random corruption but also intentional corruption by an attacker.

Third, depending on where the data comes from and where it goes to, it might be corrupted before or after being sent over the network. In that case the additional checksum inside the message might protect the integrity of the message further than just between the two network hosts.

Title: Should UDP data payloads include a CRC?


答:
You don't necessarily know what the internal representation of your data is - or may become in the future.

Assume you have a datasource which you represent as an array, you might iterate over it with a regular for loop.

Now say you want to refactor. Your boss has asked that the datasource be a database object. Furthermore he would like to have the option to pull data from an API, or a hashmap, or a linked list, or a spinning magnetic drum, or a microphone, or a realtime count of yak shavings found in Outer Mongolia.

Well if you have only one for loop you can modify your code easily to access the data object in the way it expects to be accessed.

If you have 1000 classes trying to access the data object, well now you have a big refactoring problem.

An iterator is a standard way to access a list based datasource. It's a common interface. Using it will make your code datasource agnostic.

Title: Iterator pattern - why is it important to not expose the internal representation?

Body:
I am reading C# Design Pattern Essentials. I'm currently reading about the iterator pattern.

I fully understand how to implement, but I don't understand the importance or see a use case. In the book an example is given where someone needs to get a list of objects. They could have done this by exposing a public property, such as IList<T> or an Array.

The book writes

The problem with this is that the internal representation in both of these classes has been exposed to outside projects.

What is the internal representation? The fact it's an array or IList<T>? I really don't understand why this is a bad thing for the consumer (the programmer calling this) to know...

The book then says this pattern works by exposing its GetEnumerator function, so we can call GetEnumerator() and expose the 'list' this way.

I assume this patterns has a place (like all) in certain situations, but I fail to see where and when.


问:
Including a library to use one function / utility classes
At my place of employment I have noticed a weird thing where developers will include largish libraries to do simple things. To be clear we're a Scala shop. Here are two examples that occured :

1) In one project we do CSV parsing which was originally a 3 line function. Due to the CSV creator not consistently generating the correct format this grew to cover various corner cases. A junior developer decided to bring in scala-csv for its description of CSV formats and for an Exception class. He did not integrate the parsing of CSV to use the library until prompted. Because having two ways of parsing CSv in a system is stupid we opted to use the library.

2) A senior developer bought in a scala wrapper for Joda time for its ordering ability. This was used in one isolated case. When prompted to either remove or integrate the library fully the only excuse given was "well we might need it later". Eventually the library was removed.

While both stories are different they highlight a strange mentality of just including whole libraries for utility functionality. In both cases I had to step in and insist we either integrate with the library and use its core functionality or remove it.

My question is if my insistence on either using the functionality a library offers fully or not including it / rolling your own a bad approach? My concern is that carrying a library around for utility functionality just adds dependency problems for no benefit. For example does the version of Joda the wrapper library use match our own?

答:
Libraries are about leverage. In your first case, correctly parsing CSV, for all the many, many different (mis)interpretations of CSV has already been solved in the library. It is a perfectly good thing to do this the right way. Your software is better, and smaller for it.

The primary expense of intellectual property such as computer software is the cost of maintaining and extending it. You are trying to compare the cost of three lines of software that handles some constrained data sources versus a library, that requires one line of build.sbt code, that handles almost all cases of CSV.

The real cost of those three lines is "well, I have to pre-check the data to see that properly escapes embedded newlines, and make sure the file didn't come from Joe, who embeds commas, and ..."

Edit: Regarding nose-in-the-door library inclusion:

Developers will often include libraries for no other good reason than that there is a piece of useful functionality that they can use right here and right now. There are a number of libraries that offer utility in a certain area.

Using only, let's say, the range-checking functionality of Joda Time/Scala might be comparable to using a multimeter as a small hammer. It works, but it might be missing the point. On the other hand, maybe you want to migrate more of your environment to use the much superior time handling of that library. This is an organization wide conversation that you need to have.

A much worse situation arises when a number of different libraries get included with substantially overlapping functionality. My favorite is the string checking functionality available in Apache Commons, Guava, and half a dozen other compilations. One programmer at a time Googles for function that does a particular job, and each selects a different library. This is an even more important organization wide conversation.

This whole question is strongly related to sharing classes and algorithms across your organization. It requires conversations to find out requirements, analysis of duplications and, more useful, analysis of gaps.