答:
I think you haven't totally got the idea of Responsive Web Design. Serving different HTML/CSS/JS based on the client's web-browser has been there for a while and I'm pretty sure there are still some websites still doing that -- a very clear example is the old-school way of serving a mobile-friendly theme for a website.

What you're missing, in my opinion, is that in your scenario if the user changes the view-port from portrait to landscape, then you won't get any responsive answer, unless you refresh the page. Same action is require if you resize the web-browser window or change the default zoom. Also an element in a page could be responsive to other elements as well. So, if you hide the sidebar on the right, for example, the main content will response to the change. These won't be possible in your way, again, unless you refresh the page.

Also HTTP requests are not just designed to server the whole web page. In many cases you're sending request to send/receive plain data, files, images, etc. which they don't need to carry on the view-port meta information and the overhead in a scale like Internet will be a lot I guess.

Title: Why don't HTTP headers include device resolution, pixel density, etc.?

Body:
I'm currently developing a responsive website with CSS media queries. It would be much easier if the server returned a different HTML/CSS for each viewport.

I was wondering why couldn't the client include its viewport information when requesting an HTML file. This behavior is already common for returning websites in the correct language using the Accept-Language header.


问:
How to design my code so that it can use alternative information to help create an object
I have a class named Product, which takes a product model number and number of wheels for that product as part of its creation information, and then it instantiates the product by doing a computation on the number of wheels and on various base parameters

For example, Product(5, 22) creates a model 5 product with 22 wheels on it, where that particular product's weight and dimensions are computed from the number of wheels and from the base specifications for that model number.  Right now base specifications are part of the class itself and are hardcoded into the class, along with the computation formulas.

My Issue:  in the (legacy) code I am working with, I cannot always use the model number directly.  It may not be available.  Instead, an unrelated product_id is given, where the link between product_id and model_number is in the database.

I want to keep my class as simple as possible.  As such I do not want to introduce another constructor that allows product_id as an input parameter, in addition to the existing model_number, as it will be duplication of code.  Also, I am not too keen on putting database logic inside the class, but maybe I can, as thinking about it now, this may be a good candidate for a database-wrapper class, i.e. active record (where my base specifications can be moved off from the code and into the database).

Question:  How do I create and return the object while following good object oriented principles when the model_number I typically use for its creation is not available, but another parameter is available instead (product_id in this case), which links 1:1 to model_number?

Sample solutions that I don't quite  like:

Do not involve the database -- since I am working with just a few Products at this time, and Products do not change often, I can create a "conversion function" that serves as a map between product_id and model_number and not touch the database.  Similarly, create a Convert object that has same functionality and use it before creating the object.  Problem:  duplicating DB functionality in the code.

Put DB functionality inside code and add alternate constructor.  Problem:  multiple entry-points of Product creation for the class create code duplication.

Update:

There basically are 3 aspects here:

base data (whether hardcoded or part of the database)

finding base data by various parameters be it model number or other identifying information

doing computation using base data as per model number

答:
I'd like to build upon the solution @TMN is presenting and take it a little further to answer your SRP problem. Putting database code inside the ProductFactory would be non-sensical so to encapsulate this responsibility you can create a separate class ProductModelNumberProvider with just one method findByProductId(int productId).

The ProductFactory should provide a setter setProductModelNumberProvider(ProductModelNumberProvider lookupProvider) which will assign the provider internally and call findByProductId() when appropriate.

You will have a ProductFactory which is responsible for building the product and a ProductModelNumberProvider which will do the database interaction if needed.

Have a look at your StackOverflow question for a more concrete example.

ContentLicense: CC BY-SA 3.0


问:
Programmers forgetting syntax
Do good programmers need to have syntax at the tip of their tongue when writing code? What do you make of them if they google for simple stuff online?  Are they good or bad(maybe they know where to look for)? Should programmers have a good memory? Is this a trait for a good programmer?</p>

答:
I have been writing C++ for >15 years, but I still don't know some of its arcane syntactical corners by heart.

How do you explicitly instantiate a function template again? And what's the syntax to partially specialize a template that has a template-template argument? And don't get me started about declaring a function that returns a pointer to an array of pointers to functions which take arrays of pointers to...

I suspect there's at most one or two dozen people in this world (if there are any at all) who really know all of C++' syntax by heart. And these are probably all earning their money by writing C++ compiler frontends.

ContentLicense: CC BY-SA 2.5

Title: Programmers forgetting syntax


问:
Should exceptions do things other than tell the user something went wrong?
I created a general class that accepts a string when it is constructed, and it spits out that string when a user calls what().  This is all it does; on throw, it returns the initializing string.

```<code>class Exception_As {
private:
    std::string message
public:
    Exception_As(const std::string& message) { // constructor
        this->message ="EXCEPTION: " +message;
    }

    virtual const char* what() const throw() {
        return message.c_str();
    }
}
</code>```

How I use my custom exception class:

```<code>bool check_range(
    const std::vector<std::string>& list,
    const unsigned& idx_start,  // where to start checking
    const unsigned& idx_end,    // where to stop checking
    const std::string& key
) {
    if ( idx_start > idx_end ) {
        throw Exception_As("check_range: start index > end index: now fix it! :D");
    }

    ... rest of code
} // end of check_range
</code>```

How a user would use check_range:

```<code>// some other user code using my check_range
void main() {
    try {
        ... set up variables

        my_hero_qualified = check_range(semi_finalists, third_place, first_place, my_hero);
        ...rest of code
    }

    catch (const Exception_As& e) {
        std::cout << e.what() << std::endl;
    }
}
</code>```

If the try/catch was not there, it would abort the program because of the thrown Exception_As.  If it was there, the user would be notified that "check_range: start index > end index: now fix it! :D".  For me, sure beats writing tons of BadEvent1Exception, BadEvent2Exception, etc classes.

I can see I'm being lazy with this method, and yeah, I can't do anything fancy like modify values based on exceptions or morph an object's state; but if you just entered unexpected territory, who knows if you're handling it correctly?  May as well just end it so you can fix what's up and develop properly.

So, question: if all exceptions do is break the program on unexpected circumstances, won't a single exception class that returns the problem be enough?

...Or should exceptions be doing other things anyway?  If not, why create so many classes of Exceptions that have different names, sure, but from what I've seen, only report that something went wrong.

答:
Short answer:

NO

Long answer:

You are getting the concept of exceptions wrong.

Exceptions do not tell the user there's something wrong. It's the calling program that should catch the exception and tell (or not tell) the user something is wrong or recover from it graciously.

If an "exception" has code inside to "fix" something, then it's not an exception by definition.

How can the exception get access to the context of the calling program in order to "fix it"? How does the exception knows the innards of the calling program in order to fix the error?

Also, how can a user call what() after the program aborts? Does the exception also persist the message to a file or database?

Your approach is completely new and unwritten about in books or the web.

Please show us some code.


答:
You must distinguish between exceptions for expected error conditions and exceptions that represent bugs in your program.

Let's suppose you've forbidden null in your codebase, or at least within a particular class. If you ever find a null value in one of your private variables, that unambiguously indicates a bug. It's fine to use some generic "something went wrong" exception in cases like these because it should not occur, and if it does, it should go uncaught. That way the application blows up, someone notices there's a bug, and it gets fixed. I recommend throwing an AssertionError or something similar - no one should be catching those, and it clearly expresses that some invariant of your code has been violated.

This is very different from someone calling your method with the wrong arguments, or some outside resource (e.g. files) suddenly vanishing - you know that can and likely will happen. You should provide a reasonably fine-grained exception type so that callers can distinguish different kinds of errors (i.e. don't throw GenericException everywhere).

That said, it's even better if you can write your code such that error states can't happen, or the number of error states are reduced.

Title: Should exceptions do things other than tell the user something went wrong?

Body:
I created a general class that accepts a string when it is constructed, and it spits out that string when a user calls what().  This is all it does; on throw, it returns the initializing string.

```<code>class Exception_As {
private:
    std::string message
public:
    Exception_As(const std::string& message) { // constructor
        this->message ="EXCEPTION: " +message;
    }

    virtual const char* what() const throw() {
        return message.c_str();
    }
}
</code>```

How I use my custom exception class:

```<code>bool check_range(
    const std::vector<std::string>& list,
    const unsigned& idx_start,  // where to start checking
    const unsigned& idx_end,    // where to stop checking
    const std::string& key
) {
    if ( idx_start > idx_end ) {
        throw Exception_As("check_range: start index > end index: now fix it! :D");
    }

    ... rest of code
} // end of check_range
</code>```

How a user would use check_range:

```<code>// some other user code using my check_range
void main() {
    try {
        ... set up variables

        my_hero_qualified = check_range(semi_finalists, third_place, first_place, my_hero);
        ...rest of code
    }

    catch (const Exception_As& e) {
        std::cout << e.what() << std::endl;
    }
}
</code>```

If the try/catch was not there, it would abort the program because of the thrown Exception_As.  If it was there, the user would be notified that "check_range: start index > end index: now fix it! :D".  For me, sure beats writing tons of BadEvent1Exception, BadEvent2Exception, etc classes.

I can see I'm being lazy with this method, and yeah, I can't do anything fancy like modify values based on exceptions or morph an object's state; but if you just entered unexpected territory, who knows if you're handling it correctly?  May as well just end it so you can fix what's up and develop properly.

So, question: if all exceptions do is break the program on unexpected circumstances, won't a single exception class that returns the problem be enough?

...Or should exceptions be doing other things anyway?  If not, why create so many classes of Exceptions that have different names, sure, but from what I've seen, only report that something went wrong.


问:
Unit-testing of inherently random/non-deterministic algorithms
My current project, succinctly, involves the creation of "constrainably-random events". I'm basically generating a schedule of inspections. Some of them are based on strict schedule constraints; you perform an inspection once a week on Friday at 10:00AM. Other inspections are "random"; there are basic configurable requirements such as "an inspection must occur 3 times per week", "the inspection must happen between the hours of 9AM-9PM", and "there should not be two inspections within the same 8-hour period", but within whatever constraints were configured for a particular set of inspections, the resulting dates and times should not be predictable.

Unit tests and TDD, IMO, have great value in this system as they can be used to incrementally build it while its full set of requirements is still incomplete, and make sure I'm not "over-engineering" it to do things I don't currently know I need. The strict schedules were a piece-o'-cake to TDD. However, I'm finding it difficult to really define what I'm testing when I write tests for the random portion of the system. I can assert that all times produced by the scheduler must fall within the constraints, but I could implement an algorithm that passes all such tests without the actual times being very "random". In fact that's exactly what's happened; I found an issue where the times, though not predictable exactly, fell into a small subset of the allowable date/time ranges. The algorithm still passed all assertions I felt I could reasonably make, and I could not design an automated test that would fail in that situation, but pass when given "more random" results. I had to demonstrate the problem was solved by restructuring some existing tests to repeat themselves a number of times, and visually check that the times generated fell within the full allowable range.

Does anyone have any tips for designing tests that should expect non-deterministic behavior?

Thanks to all for the suggestions. The main opinion seems to be that I need a deterministic test in order to get deterministic, repeatable, assertable results. Makes sense.

I created a set of "sandbox" tests that contain candidate algorithms for the constraining process (the process by which a byte array that could be any long becomes a long between a min and max). I then run that code through a FOR loop that gives the algorithm several known byte arrays (values from 1 to 10,000,000 just to start) and has the algorithm constrain each to a value between 1009 and 7919 (I'm using prime numbers to ensure an algorithm wouldn't pass by some serendipitous GCF between the input and output ranges). The resulting constrained values are counted and a histogram produced. To "pass", all inputs must be reflected within the histogram (sanity to ensure we didn't "lose" any), and the difference between any two buckets in the histogram cannot be greater than 2 (it should really be <= 1, but stay tuned). The winning algorithm, if any, can be cut and pasted directly into production code and a permanent test put in place for regression.

Here's the code:

```<code>    private void TestConstraintAlgorithm(int min, int max, Func<byte[], long, long, long> constraintAlgorithm)
    {
        var histogram = new int[max-min+1];
        for (int i = 1; i <= 10000000; i++)
        {
            //This is the stand-in for the PRNG; produces a known byte array
            var buffer = BitConverter.GetBytes((long)i);

            long result = constraintAlgorithm(buffer, min, max);

            histogram[result - min]++;
        }

        var minCount = -1;
        var maxCount = -1;
        var total = 0;
        for (int i = 0; i < histogram.Length; i++)
        {
            Console.WriteLine("{0}: {1}".FormatWith(i + min, histogram[i]));
            if (minCount == -1 || minCount > histogram[i])
                minCount = histogram[i];
            if (maxCount == -1 || maxCount < histogram[i])
                maxCount = histogram[i];
            total += histogram[i];
        }

        Assert.AreEqual(10000000, total);
        Assert.LessOrEqual(maxCount - minCount, 2);
    }

    [Test, Explicit("sandbox, does not test production code")]
    public void TestRandomizerDistributionMSBRejection()
    {
        TestConstraintAlgorithm(1009, 7919, ConstrainByMSBRejection);
    }

    private long ConstrainByMSBRejection(byte[] buffer, long min, long max)
    {
        //Strip the sign bit (if any) off the most significant byte, before converting to long
        buffer[buffer.Length-1] &= 0x7f;
        var orig = BitConverter.ToInt64(buffer, 0);
        var result = orig;
        //Apply a bitmask to the value, removing the MSB on each loop until it falls in the range.
        var mask = long.MaxValue;
        while (result > max - min)
        {
            mask >>= 1;
            result &= mask;
        }
        result += min;

        return result;
    }

    [Test, Explicit("sandbox, does not test production code")]
    public void TestRandomizerDistributionLSBRejection()
    {
        TestConstraintAlgorithm(1009, 7919, ConstrainByLSBRejection);
    }

    private long ConstrainByLSBRejection(byte[] buffer, long min, long max)
    {
        //Strip the sign bit (if any) off the most significant byte, before converting to long
        buffer[buffer.Length - 1] &= 0x7f;
        var orig = BitConverter.ToInt64(buffer, 0);
        var result = orig;

        //Bit-shift the number 1 place to the right until it falls within the range
        while (result > max - min)
            result >>= 1;

        result += min;
        return result;
    }

    [Test, Explicit("sandbox, does not test production code")]
    public void TestRandomizerDistributionModulus()
    {
        TestConstraintAlgorithm(1009, 7919, ConstrainByModulo);
    }

    private long ConstrainByModulo(byte[] buffer, long min, long max)
    {
        buffer[buffer.Length - 1] &= 0x7f;
        var result = BitConverter.ToInt64(buffer, 0);

        //Modulo divide the value by the range to produce a value that falls within it.
        result %= max - min + 1;

        result += min;
        return result;
    }
</code>```

... and here's the results:

LSB rejection (bit-shifting the number until it falls within the range) was TERRIBLE, for a very easy-to-explain reason; when you divide any number by 2 until it's less than a maximum, you quit as soon as it is, and for any non-trivial range, that will bias the results towards the upper third (as was seen in the detailed results of the histogram). This was exactly the behavior I saw from the finished dates; all of the times were in the afternoon, on very specific days.

MSB rejection (removing the most significant bit off the number one at a time until it's within the range) is better, but again, because you're chopping off very large numbers with each bit, it's not evenly distributed; you're unlikely to get numbers in the upper and lower ends, so you get a bias toward the middle third. That might benefit someone looking to "normalize" random data into a bell-ish curve, but a sum of two or more smaller random numbers (similar to throwing dice) would give you a more natural curve. For my purposes, it fails.

The only one that passed this test was to constrain by modulo division, which also turned out to be the fastest of the three. Modulo will, by its definition, produce as even a distribution as possible given the available inputs.

答:
Your goal is not to write unit tests and pass them, but to make sure that your program fits its requirements. The only way you can do this, is to precisely define your requirements in the first place. For example, you mentioned "three weekly inspections at random times". I'd say the requirements are: (a) 3 inspections (not 2 or 4), (b) at times that are not predictable by people who don't want to be inspected unexpectedly, and (c) not too close together - two inspections five minutes apart are probably pointless, maybe not too far apart either.

So you write down the requirements more precisely than I did. (a) and (c) are easy. For (b), you might write some code as clever as you can that tries to predict the next inspection, and to pass the unit test, that code must not be able to predict better than pure guess.

And of course you need to be aware that if your inspections are truly random, any prediction algorithm could be correct by pure chance, so you must be sure that you and your unit tests don't panic if that happens. Maybe perform a few more tests. I wouldn't bother testing the random number generator, because in the end it's the inspection schedule that counts, and it doesn't matter how it was created.

ContentLicense: CC BY-SA 4.0


问:
Implementing the Interface Segregation Principle
Does this IConvertible interface satisfy the Interface Segregation Principle (ie. the "I" in SOLID)?

Here is the definition:

```<code>public interface IConvertible
{
    TypeCode GetTypeCode();
    bool ToBoolean(IFormatProvider provider);
    byte ToByte(IFormatProvider provider);
    char ToChar(IFormatProvider provider);
    DateTime ToDateTime(IFormatProvider provider);
    decimal ToDecimal(IFormatProvider provider);
    short ToInt16(IFormatProvider provider);
    int ToInt32(IFormatProvider provider);
    long ToInt64(IFormatProvider provider);
    sbyte ToSByte(IFormatProvider provider);
    float ToSingle(IFormatProvider provider);
    string ToString(IFormatProvider provider);
    object ToType(Type conversionType, IFormatProvider provider);
    ushort ToUInt16(IFormatProvider provider);
    uint ToUInt32(IFormatProvider provider);
    ulong ToUInt64(IFormatProvider provider);
}
</code>```

So if I would like to have a class which will implements this IConvertible interface the I have to implement all of those methods, right? Or if I don't implement all of them, then I have to at least make an empty method or throw an Exception, right?.

In my opinion, the better way is to make more interface with fewer methods, for example:

```<code>public interface IConvertibleInt
{
        short ToInt16(IFormatProvider provider);
        int ToInt32(IFormatProvider provider);
        long ToInt64(IFormatProvider provider);
}
</code>```

Or even:

```<code>public interface IConvertibleInt16
{
        short ToInt16(IFormatProvider provider);
}

public interface IConvertibleInt32
{
        int ToInt32(IFormatProvider provider);
}

public interface IConvertibleInt64
{
        long ToInt64(IFormatProvider provider);
}
</code>```

Is my reasoning correct?

答:
One difficulty with applying the Interface Segregation Principle in .NET is that any given storage location must have a single specified type.  If there had been separate interfaces for IConvertibleToInt32, IConvertibleToInt64, then a type which only supported some of the conversions would only have to implement the ones it supported; code which needed exactly one conversion interface could accept a parameter of that type.  Unfortunately, splitting things up in that fashion would make it difficult to write code which needs more than one conversion interface.  For example, if a method needed to use IConvertibleToInt32, but which needed to pass an object to a method that needed IConvertibleToInt64, there would be no way to specify that it needed an object which supported both interfaces unless there were existed an interface which inherited from both and all types of interest which implement both interfaces also implement the composite one.

If .NET made had a means of defining a special kind of "composite" interface such that any class which implemented all of the components would automatically be regarded as an implementation of the composite, then it would make sense to subdivide interfaces much more finely.  The lack of such ability, however, makes it necessary to define interfaces which are much coarser than would be ideal.


问:
Why don't HTTP headers include device resolution, pixel density, etc.?
I'm currently developing a responsive website with CSS media queries. It would be much easier if the server returned a different HTML/CSS for each viewport.

I was wondering why couldn't the client include its viewport information when requesting an HTML file. This behavior is already common for returning websites in the correct language using the Accept-Language header.

答:
Are you sure you're doing responsive design?  Responsive design is technically the combination of fluid design and media queries.

Fluid design solves 90% of the viewport issue for you, if you are smart about how you lay things out.  Media queries get you the other 10% by changing grid characteristics based on current dimensions.

If you're trying to do only fluid (percentages everywhere, relative sizing on everything,  nothing specified in pixels, etc.) you run into the problem of what to do when the viewport is dramatically different in size (like a desktop landscape view vs. a mobile portrait view).  Some things simply don't fit when you go from 2048px to 640px.  When you try to do only media queries, you end up with dozens and dozens of media query breaks, and you're basically micromanaging your CSS classes in that case.  Neither approach is adequate for RWD -- you have to combine the two to get everything.

My advice:  create three or four different "nominal resolutions and orientations"  -- like Desktop landscape, iPad portrait and landscape, iPhone portrait and landscape -- and treat them as your wireframes to work from.  Then set up your media queries for those breaks.  Then work really hard to stick to those few breaks, using fluid layouts to accomplish it -- most likely with a CSS grid of some kind (there are dozens of them prebuilt for you, or you can roll your own).


问:
Should an API be aware of client versions?
Should an API be aware of a client version?

The idea of that really goes against the grain for me, but it seems like it is being pushed for in my current project.

Am I wrong? Can I get some reasons for or against this that I can present or understand why it might be good.

The API is a RESTful API.

答:
Almost without exception, no.  Methods represent behaviors.  Behaviors generally aren't supposed to change depending on who the consumer is.  For example, when you walk into a restaurant, do you expect to get treated differently because of your gender or your skin color?  Of course not.  The implicit contract that every restaurant makes with the world is:  "You come into my restaurant, I hand you a menu from which to pick things, and you eat the thing you selected."  The fact that I might not know what one of the foods is is irrelevant.  That's MY problem, not the restaurant's problem.  The restaurant can't become a hair salon, simply because that's what I, as a client, want or expect.  That's one of the ways we end up with the God Object antipattern.  Clearly defining client and producer responsibilities is super important in OOAD.

So, that's the rule.  There are some corner-case exceptions to it, but at the moment they aren't coming to mind.


答:
Although I agree with @dan1111 that a server has no business acting different according to the client version, I can see a case where you add a feature to one of the APIs and:

You don't want to change its name/end-point/whatever just to differentiate it from the previous version, because you plan to deprecate the previous version, and don't want the API to suffer from long term readability or cumbersome naming for all eternity

You want to roll-out your new feature, but during the roll-out you have both the new client, and the old client, who does not know how to handle the new feature

Your planned roll-out is short term enough that you know that within X days, the old client will be (for all practical purposes) extinct

In this case, I think it is a viable strategy to add your feature in a defensive way, adding ad-hoc code to support the old client as to not break it, until your roll-out is complete.

After that period, you can safely remove the ad-hoc code, so you don't end up with a patchy, encumbered code.

Title: Should an API be aware of client versions?

Body:
Should an API be aware of a client version?

The idea of that really goes against the grain for me, but it seems like it is being pushed for in my current project.

Am I wrong? Can I get some reasons for or against this that I can present or understand why it might be good.

The API is a RESTful API.


问:
Run coded UI tests on different projects
With little or none previous experience of testing, I'm looking into adding automated testing to a continuous integration process of SharePoint applications. I've learned how this can be achieved using coded UI tests that are run before deployment and during the build and I've used Selenium with Java before, where we didn't record any scenarios but instead wrote tests by hand, identifying elements in the GUI and asserting results. With this little experience, I have a few questions about UI testing.

Is it possible to write test methods that can be applied on several different applications, such as testing buttons etc. or is this something that has to be written for each project, since the results of button click may vary? I assume that this would require following a specific standard .

Are there any UI testing methods that can be generalized and applied to all projects that go through a certain build, or is the same here that all UI tests must be written specifically for that application?

答:
Is it possible? Sure it is.

Is it recommended? That's a tougher question - automated tests are created to validate the functionality of your application. Generic testing can only test generic functionality.

I can see two main use-cases where you might find yourself contemplating on generic testing:

Testing applications which use the same boilerplate functionality, because they use the same library, framework, etc.

Testing application which should abide to the same standards which were decided in some meta-application policy in your company.

For the first case, I think the correct approach is to unit test the library/framework in the context of that library or framework, and leave only high-level sanity/integration tests on each application, to see that it uses that library correctly. There is no need to test the same code in different applications - it is the same code, after all...

For the second case, your company might decide to write generic acceptance tests to make sure that every application adheres to the needed standards, in which case, it seems reasonable from the point of view of the QA team to run the same tests on every application, given that the requirements and tests are robust enough to handle applications which might be very different on many other aspects.


问:
How to use namespaces to separate interface from implementation, in c++?
As far as I can tell, you can make your interface known to others by providing your .h file.  Your .cpp is the implementation.  Then they can see the function names, the parameter types, the return type, maybe a description of how to use a function, and maybe what it does in the .h file.

Then I read in posts here about using namespaces to separate the interface from the implementation.  What does that mean?  Doesn't a namespace only let you know that a name exists in that namespace?  So please provide an example, I can't find any.

答:
You don't use namespaces to separate interface from implementation in C++.  Namespaces are essentially packages in C++; you use them to group together related classes.

Rather, you use classes to hide the implementation details from the user.  Classes in C++ are the same as classes in any other OOP language in that regard; they provide a public interface, while encapsulating the implementation details.

In the Stack Overflow answer that you linked, the author linked this article.  In a nutshell, this article states that any helper functions and operator functions that are part of the functionality of a class should go into the same namespace as that of the class, because they form part of the public API of that namespace.

That makes sense to me.  Having those functions in the same namespace organizes the classes (and the functions that support them) within the same logical unit, a logical unit that exposes a public API, but encapsulates the implementation details using ordinary object orientation principles.

Further Reading

Separating Interface and Implementation in C++

The Separation of Interface and Implementation in C++

Namespaces and the Interface Principle


问:
Create Database To Fit Data vs Make Data Fit The Database
I'm newish to programming and would like to know what people have found to be the most supportable option or rather what people find more understandable.  I'm the only one writing code at my firm, but gradually will hand this off to someone else in the future.

The Project

The project I'm working on is parsing a huge text file that comes in once a day.  The data file uses previous day's data file as a reference so each data file builds upon the previous data file. Using documentation I'm able to parse the text file and populate a MySQL database.  Once the text file has been read, the data in the database is manipulated and then dumped into many Excel workbooks.  The text file has a huge amount of data and I only need a fraction of it for the Excel workbooks.

My Question

My question is what is the proper structure for this program?  I see that I have two options.

Is it better to construct a database that fits the data.  So create a database with more tables and fields then is actually needed and possibly a little cryptic in it's layout.

Is it better to manipulate the data while it's being parsed and put it into more readable, human database?

What I've Done So Far

When I wrote the first version of this program, I went for option 2.  Since I didn't know much about relational databases at the time and wanted it very easy for me to understand, visualize, etc.  However, now that I'm looking to expand the data that I parse from the text file and since each data file builds on the previous day's data file I'm leaning towards option 1 so later down the line I won't have to spend a day reconstructing the database.

Does this make sense?  Please comment if it doesn't. Any help would be greatly appreciated.

thanks,
Justin

Update

Let me start by saying the answers so far have been very helpful.  Thank you. After reading some comments though I find that I have been a bit vague in my question.  Let me try to be a bit clearer.  I'm dealing with financial data of clients.  Each account has its own Excel workbook that is used by the financial advisors to make projections and investment decisions.  Additional worksheets in the the workbook are used to display the account's holdings and projected future to the client.  The data that I get in each data file is separated by a record.  Each record has a type...there are something like 13 different record types.  Each record type is marked by a particular letter or number.  Then after that letter or number there are a specific number of characters that represent that particular record.  The record layout differs per record type and there is redundant information between record types which makes it additionally aggravating.  Another point of contention is that if the financial advisor buys a new security, one that s/he hasn't bought before then the next business day, only in that day's data file, will the security's information show up (such as the name, security type, etc) and not again unless there's a change in that security.  So if I ever need to rebuild the database I would have to start from day one.

So I'm taking this data file, parsing it and writing it to a MySQL database separated into about four tables.  I use EF6 to work with the database, and so that was a reason I started with a simple, readable fields and tables.  Hope this expanded explanation helps.

答:
A well designed relational database will generally have tables made for optimal data storage. Of course there can be exceptions depending on your scenario (pretty much every database I've worked with has been denormalized at some point), but you must always try to favor enforced data structure over easy data retrieval. This will make your data safer and harder to get corrupted.

Since you mentionned you are using mysql, views will be your friend if you want to ease up data retrieval. Views are reusable queries made on top of your table or other views. You can have as many as you need and it won't affect how your data is structured in any way.


问:
Why isn't java used as a build language?
If Java is a general purpose language, and building a program is something that can be described using the Java language, why isn't this the best way to write build files and instead we use tools like Ant, Maven, and Gradle? Wouldn't that be more straightforward, and also remove the need to learn yet another programming language?
(BTW - this question can also be applied to other languages, like C#)</p>

答:
Java is an imperative language, Ant, Maven, etc. are declarative languages:

We could define the difference as follows:

Imperative programming: telling the "machine" how to do something, and
  as a result what you want to happen will happen.

Declarative
  programming: telling the "machine" what you would like to happen, and
  let the computer figure out how to do it.1

Build languages tell the builder what should be done, from where it should be taken, etc. The engine which runs the build (which is written in an imperative language, like @ElliottFrisch has noted), reads these instructions, and fulfills them.

Declarative languages may seem more appropriate in build scenarios, since build tasks are generally the same all over, and it is considered more maintainable and readable in that form than in full-fledged code form.


答:
Keep it small and simple.

You mention your text file has a lot of data in it that you don't need.  If you stuff all of that in your database, you'll have a much more complicated / harder to understand structure that the next person will have to decipher.

Can you imagine inheriting a large complicated structure where only 10% is in actual use?

See also this SO question and Jeff Atwood's blog article, Coding for Violent Psychopaths

By all means code up the stuff you need.  Follow best database practices, normalize within reason, use views, foreign keys, and indices, and jealously guard data integrity with a vengeance.

Just don't build a bunch of junk "that you might need someday".

YAGNI is your friend.

Title: Create Database To Fit Data vs Make Data Fit The Database

Body:
I'm newish to programming and would like to know what people have found to be the most supportable option or rather what people find more understandable.  I'm the only one writing code at my firm, but gradually will hand this off to someone else in the future.

The Project

The project I'm working on is parsing a huge text file that comes in once a day.  The data file uses previous day's data file as a reference so each data file builds upon the previous data file. Using documentation I'm able to parse the text file and populate a MySQL database.  Once the text file has been read, the data in the database is manipulated and then dumped into many Excel workbooks.  The text file has a huge amount of data and I only need a fraction of it for the Excel workbooks.

My Question

My question is what is the proper structure for this program?  I see that I have two options.

Is it better to construct a database that fits the data.  So create a database with more tables and fields then is actually needed and possibly a little cryptic in it's layout.

Is it better to manipulate the data while it's being parsed and put it into more readable, human database?

What I've Done So Far

When I wrote the first version of this program, I went for option 2.  Since I didn't know much about relational databases at the time and wanted it very easy for me to understand, visualize, etc.  However, now that I'm looking to expand the data that I parse from the text file and since each data file builds on the previous day's data file I'm leaning towards option 1 so later down the line I won't have to spend a day reconstructing the database.

Does this make sense?  Please comment if it doesn't. Any help would be greatly appreciated.

thanks,
Justin

Update

Let me start by saying the answers so far have been very helpful.  Thank you. After reading some comments though I find that I have been a bit vague in my question.  Let me try to be a bit clearer.  I'm dealing with financial data of clients.  Each account has its own Excel workbook that is used by the financial advisors to make projections and investment decisions.  Additional worksheets in the the workbook are used to display the account's holdings and projected future to the client.  The data that I get in each data file is separated by a record.  Each record has a type...there are something like 13 different record types.  Each record type is marked by a particular letter or number.  Then after that letter or number there are a specific number of characters that represent that particular record.  The record layout differs per record type and there is redundant information between record types which makes it additionally aggravating.  Another point of contention is that if the financial advisor buys a new security, one that s/he hasn't bought before then the next business day, only in that day's data file, will the security's information show up (such as the name, security type, etc) and not again unless there's a change in that security.  So if I ever need to rebuild the database I would have to start from day one.

So I'm taking this data file, parsing it and writing it to a MySQL database separated into about four tables.  I use EF6 to work with the database, and so that was a reason I started with a simple, readable fields and tables.  Hope this expanded explanation helps.


问:
How often do you run & test your code while programming?
Especially when writing new code from scratch in C, I find myself writing code for hours, even days without running the compiler for anything but an occasional syntax check.

I tend to write bigger chunks of code carefully and test thoroughly only when I'm convinced that the code does what it's supposed to do by analysing the flow in my head. Don't get me wrong - I wouldn't write 1000 lines without testing at all (that would be gambling), but I would write a whole subroutine and test it (and fix it if necessary) after I think I'm finished.

On the other side, I've seen mostly newbies that run & test their code after every line they enter in the editor and think that debuggers can be a substitute for carefulness and sanity. I consider this to be a lot of distraction once you've learned the language syntax.

What do you think is the right balance between the two approaches? Of course the first one requires more experience, but does it affect productivity positively or negatively? Does the second one help you spot errors at a finer level?

答:
I find myself writing code for hours, even days without running the compiler for anything but an occasional syntax check.

Hours to days - that's a clear sign that you miss the ability to break down your code into smaller chunks which can be verified and tested on their own. You should definitely work on that.

I tend to write bigger chunks of code carefully and test thoroughly only when I'm convinced that the code does what it's supposed to do by analysing the flow in my head.

Instead of writing bigger - and thus complicated - chunks of code which needs hours to be analysed in your head, you should try to create smaller, not so big building blocks. This is called building abstractions - and that's the gist of good programming, definitely not a sign of beeing a newbie.

Excellent programming is like excellent Billard playing - a good player does not play hard strokes. Instead, he plays in a way where after each stroke the balls stop in a position where the next stroke is easy again. And a programmer is not good because he can write complicated code - he is good because he can avoid writing complicated code.


问:
How can I use different versions of an evolving library in different projects?

The problem

I write a lot of exploratory code in my research. As I go along, I put functionality that I'd like to reuse in a central location. A project might look like this:

```<code>./mylib
./exploration
    /experiment_1
    /experiment_2
    /experiment_3
</code>```

Where each experiment uses some functionality from mylib.

Now I come along and start my fourth experiment. In the process, I may need to change my library in some backwards-incompatible way. Now I can't re-run my first three experiments without updating their codes to be compatible with the newest library.

Note: As of now, I keep mylib in version control, and exploration in version control, using git. This means that all of the experiments are in the same repository. This is done so that a single push or fetch and merge in experiments syncs all of my experiments between computers. I feel that there may be a better way, but that might be for another question...

Possible solutions

I could bite the bullet and update the old experiments manually whenever I need to run them (bad, tedious, but straightforward).

I could "vendorize" my library by copying it whenever I make a new experiment. (Bad, bugfixes have to be inserted into each copy).

Since I keep my library in version control, I could tag points in the library's history by whatever is required by an experiment. When I want to run experiment n, I'd checkout tag n. (Better, but what if I want to run two experiments simultaneously? It also seems like there should be a way to automatically use a specific version of the library.)

Whenever I start an experiment, I'll make a new branch in the library. In each experiment folder, I'll clone the library repo and checkout the correct branch. (This seems reasonable, though it is perhaps wasteful of space, since I'm duplicated all branches when I clone. Also, I might have a lot of experiments, meaning that there will be lots and lots of branches in my repository, cluttering things unnecessarily.)

Should I reconsider any of these above solutions?

I have also heard about git's subtrees and submodules, and while they sound like they might be the answer to my problem, I want to get the input of more knowledgeable coders before sinking time into a rabbit-hole.

答:
After spending the afternoon reading, it looks like git subtree is what I'm after. In this approach, I keep my library in version control with git, and each experiment goes into a separate repository. When I start an experiment, I pull the latest version of the library in in with a git subtree add. Each experiment has its own version of the library. If I want to update an experiment to use a new version of the library, I can make a branch, do a git subtree pull, patch up my experiment code to work with the new interface, and merge back into master.

The great thing about git subtree is that the history of the experiment is tied to the history of the library that I am using. This is incredibly useful in exploratory research where reproducibility is paramount. For example, I might run an experiment with version 1 of a library and get a certain result. Later, after updating the experiment's code and moving to version 2 of the library, I might re-run the experiment and find, to my surprise, that the result is different. With subtrees, if I have the commit hash that produced my original result, I can restore my experiment to the exact state it was when I ran it originally, library and all, by simply checking out that commit.


问:
Removing dependencies on subclass-specific behavior
I have a Message class which can contain multiple types of payloads (or sometimes no payload), each derived from a common Payload class. However, this becomes problematic because the Message class wants to know about the Payload subclasses for various reasons such as:

Checking for Message equality

```<code>if (message parts besides the payload are equal) {
    switch(type) {
        case Payload::Type::RESPONSE:
            return *static_cast<ResponsePayload*>(payload.get())
                == *static_cast<ResponsePayload*>(o.payload.get());
            break;

        case Payload::Type::SETUP:
            return *static_cast<SetupPayload*>(payload.get())
                == *static_cast<SetupPayload*>(o.payload.get());
            break;

        ...
    }
}
</code>```

Deserializing (since the deserialization methods are static because the payloads are immutable)

```<code>switch(type) {
    case Payload::Type::RESPONSE:
        load = ResponsePayload::fromJSON(payloadValue);
        break;

    case Payload::Type::SETUP:
        load = SetupPayload::fromJSON(payloadValue);
        break;

    ...

    case Payload::Type::START:
    case Payload::Type::STOP:
    case ...:
        break; // Load stays null

    default:
        THROW(Exception, "Error in program logic: we forgot to parse some payload");
}
</code>```

Ensuring a Payload is attached to a Message while constructing it:

```<code>switch(type) {
    case Payload::Type::RESPONSE:
    case Payload::Type::SETUP:
    case ...:
        ENFORCE(IOException, payload != nullptr, "For this message type, a payload is required.");
        break;

    case Payload::Type::START:
    case Payload::Type::STOP:
    case ...:
        ENFORCE(IOException, payload == nullptr, "For this message type, the payload should be null");
        break;

    default:
        THROW(Exception, "Error in program logic: we forgot to handle some payload");
}
</code>```

Alarm bells are going are going off in my head - this violates SOLID like there's no tomorrow and obviously doesn't scale well since I have to add case statements every time I add a new payload. Is there a cleaner approach I could take?

答:
Alarm bells should be going off. But some top of my head initial suggestions (meaning I didn't take the time to come up with the best solution, just a much better one than you've got).

1 - Why is there a separate Message and Payload class, aren't they the same thing?

2 - Include the equality check in the subclasses where they take a payload instance as the parameter. Subclasses only know about their own type. If you pass a payload that isn't the right type then the type conversion will fail and you know they aren't equal.

3 - Create a Payload factory instead of creating all the various types in the base message class.

4 - Subclass the Message class if it requires parameters to be built properly.


答:
What I actually ended up doing:

At first I was wondering if I am better off with such complexity.

Simpler way was:

There is another pattern here that I could use that keeps things in one class:  https://stackoverflow.com/a/2175213/2883328.  Breaks SRP.

```<code>$product = Product::fromProductId($productId, $wheels);
</code>```

SRP way (chosen)

ProductData class that just has the data (can be swapped by database later)

ProductFactory class that uses Provider class to look up the model number

ProductNumberProvider class that provides model number when given product id

Product class that does loads ProductData and does computations

Code:

```<code>$provider = new ProductModelNumberProvider();
$factory = new ProductFactory($provider);
$product = $factory->constructFromProductId($productId, $wheels);
</code>```

Title: How to design my code so that it can use alternative information to help create an object

Body:
I have a class named Product, which takes a product model number and number of wheels for that product as part of its creation information, and then it instantiates the product by doing a computation on the number of wheels and on various base parameters

For example, Product(5, 22) creates a model 5 product with 22 wheels on it, where that particular product's weight and dimensions are computed from the number of wheels and from the base specifications for that model number.  Right now base specifications are part of the class itself and are hardcoded into the class, along with the computation formulas.

My Issue:  in the (legacy) code I am working with, I cannot always use the model number directly.  It may not be available.  Instead, an unrelated product_id is given, where the link between product_id and model_number is in the database.

I want to keep my class as simple as possible.  As such I do not want to introduce another constructor that allows product_id as an input parameter, in addition to the existing model_number, as it will be duplication of code.  Also, I am not too keen on putting database logic inside the class, but maybe I can, as thinking about it now, this may be a good candidate for a database-wrapper class, i.e. active record (where my base specifications can be moved off from the code and into the database).

Question:  How do I create and return the object while following good object oriented principles when the model_number I typically use for its creation is not available, but another parameter is available instead (product_id in this case), which links 1:1 to model_number?

Sample solutions that I don't quite  like:

Do not involve the database -- since I am working with just a few Products at this time, and Products do not change often, I can create a "conversion function" that serves as a map between product_id and model_number and not touch the database.  Similarly, create a Convert object that has same functionality and use it before creating the object.  Problem:  duplicating DB functionality in the code.

Put DB functionality inside code and add alternate constructor.  Problem:  multiple entry-points of Product creation for the class create code duplication.

Update:

There basically are 3 aspects here:

base data (whether hardcoded or part of the database)

finding base data by various parameters be it model number or other identifying information

doing computation using base data as per model number

Body:
What I actually ended up doing:

At first I was wondering if I am better off with such complexity.

Simpler way was:

There is another pattern here that I could use that keeps things in one class:  https://stackoverflow.com/a/2175213/2883328.  Breaks SRP.

$product = Product::fromProductId($productId, $wheels);

SRP way (chosen)

ProductData class that just has the data (can be swapped by database later)

ProductFactory class that uses Provider class to look up the model number

ProductNumberProvider class that provides model number when given product id

Product class that does loads ProductData and does computations

Code:

$provider = new ProductModelNumberProvider();
$factory = new ProductFactory($provider);
$product = $factory->constructFromProductId($productId, $wheels);


问:
Citations for inadvisability of globally unique password
I am having a disagreement with a client about the user authentication process for a system. The nub of it is that they want each user to have a globally unique password (i.e. no two users can have the same password).

I have wheeled out all the obvious arguments against this:

it's a security vulnerability,

it confuses identification with authentication,

it's pointless, etc.,

but they are insisting that there is nothing wrong with this approach.

I have done various gGoogle searches looking for authoritative (or semi-authoritative , or even just independent) opinions on this, but can't find any (mainly it's just such an obvious faux pas that it doesn't seem worth warning against, as far as I can tell).  Can anybody point me towards any such independent opinion, please?

EDIT: Thanks for all your answers, but I already understand the problems with this proposed approach/requirement, and can even explain them to the client, but the client wont't accept them, hence my request for independent and/or authoritative sources.

I'd also found the Daily WTF article, but it suffers from the problem that Jon Hopkins has pointed out - that this is such a self-evident WTF that it doesn't seem worth explaining why.

And yes, the passwords are going to be salted and hashed. In which case global uniqueness might well be difficult to ensure, but that doesn't solve my problem - it just means that I have a requirement that the client won't budge on, that's not only ill-advised, but is also difficult to implement. And if I was in a position to say "I'm not budging on salting and hashing", then I'd be in a position to say "I'm not implementing globally unique passwords".

Any pointers to independent and/or authoritative sources for why this is a bad idea still gratefully received...

答: Just thinking in terms of appropriate place to ask the question, the IT security section of Stack Exchange should be a useful point for you. Try https://security.stackexchange.com/questions/tagged/passwords - a range of individuals focused on IT Security should be able to provide specific answers.</p>


问:
What are the origins of the Public/Private function declarations?

The Question

What are the origins of the Public/Private function paradigm?

Background

A question came up in chat about Header files in C, and their usage being mainly to help the compiler, not the programmer. It's my understanding though, that this is the first usage of the concept of "Private" functions, or functions which aren't prototyped in the header file. Had C not used header files to declare functions, would we still have the current concept of Public and Private functions as seen in C# or Java? Or was this concept initially developed elsewhere and simply implemented in the C Header/Source scheme

答:
I think the idea of making parts of your code private has roots which goes further back than Simula. Scheme (1975) was the first language to implement closures, which gives you the possibility to encapsulate data such as lambdas. Schema also lets you specify internal functions using the define keyword.

Making functions private allows more abstraction to be incorporated into a program. Building abstractions in programs has a long history, with LISP-variant languages such as Scheme contributing a lot to the development of modern programming languages.

Structure and Interpretation of Computer Programs by Abelson, Sussman is an excellent book to learn more about abstractions if you are interested in those things.


问:
Is there a loophole in the GPL that allows proprietary software to be linked with GPL libraries?
Let’s examine a hypothetical scenario:

Company X writes a proprietary program (A) that dynamically links with a proprietary library (B). Company Y wants to use a replacement library (C) licensed under the GPL, and so writes a wrapper library (D) that dynamically links to both A and C and translates the API calls used by A to the API calls used by C.

As D is intended to be used with C, and uses C’s API calls, it is a derivative work of C and must therefore be distributed under the terms of the GPL*. As a result, the combined work of A and D must also be distributed under the terms of the GPL, which is impossible given that Company Y does not possess the source code for A. That said, so long as Company Y distributes D by itself, there is no problem. However, regardless of Company Y’s actions, Company X does not violate the GPL by distributing A, even without B. The mere existence of D does not mean that A is suddenly a derivative work of C (through D) that must be licensed under the GPL as well.

Now this is the loophole: there is nothing that stops Company X from writing its own version of D, distributing it separately from A, and telling end-users to use D instead of B when running A. It seems that a company is capable of designing a proprietary program to use a GPL library without violating the GPL, so long as a wrapper module is used to insulate the proprietary program from the GPL library and that module is distributed separately.

Am I correct in my reasoning? Is this a real loophole in the GPL?

*D is also a derivative work of A, but for the purposes of this scenario, Company X has explicitly authorized the creation of D and allowed it to be licensed under the GPL.

答:
Linking defines a derivative by the GPL. This specific situation is what the LGPL was designed to handle: where you want to release the library as GPL but define linking as the explicit limit of the applied license, or alternately, where you want to link against some GPL code but require that your own work be released under a non-GPL license itself.

In the case where the end-user is going to do the linking (build his own code from non-GPL sources which may link against a GPL library) the end-user has not effectively created a GPL version of whatever the final product is, as he is not permitted to change the license of the non-GPL portion of the project because he is not the owner of it. This generally precludes distribution by the end-user in any form, but would not prohibit use.

That said, if a project requires that it be built from source and is only distributed that way it is irrelevant what license the linked library is under, as this is entirely out of the non-GPL developer's hands. That is, how can you know your source-only distribution is going to be built on gcc against glibc VS built on an IBM compiler against their libc unless you specify this under your own licensing terms? This quickly runs into fair-use and prohibitions against unenforceable legal conditions (not that fantasy hasn't been written into law on quite a few occasions recently).


问:
Slight extension for SQL prepared statements syntax. Need advice
In my database abstraction library I am extending SQL prepared statements syntax to hint a parser with expected literal type. I take it as a very essential improvement, my reasoning you can read here. If you want to question the idea itself, please let me know in the comments - I'd like to start another question instead of mixing it here.

The advice I want is on the syntax. I am quite ignorant of all the languages and dialects beside php and mysql, and may be there already a general purpose solution I am unaware of. If not - then I want to know your personal opinion or suggestion.

At the moment, only positional placeholders supported. Yet I was asked many times to add support for the named ones. However, I cannot decide which syntax to choose for that.

At the moment I mark a conventional question mark with single letter, i.e. ?s - string, ?i - int, ?n - name (identifier) and so forth.

Yet for the named placeholder (:name style) the only sane option to me is

```<code>i:name
</code>```

or, if I decide to add more verbose modifiers, even

```<code>int:name
</code>```

so, the query would look like

```<code>SELECT * FROM ident:table WHERE id IN (int:id)
</code>```

The question is: do you see any drawbacks for such a syntax? Do you have a suggestion for any other style? Do you think it's readable at all?

Another question is on repeating things. At the moment I have two placeholders for the arrays - ?a for the comma separated string list and ?u for the ?n=?s pairs. It bugs me a long time already, that such a syntax is superfluous, yet insufficient. What if I need a set of comma-separated identifiers? Or even a complex statement like whole VALUES clause? With some sort of repetition operator I can make SQL query building dramatically better. Here are examples of what I am thinking of:

```<code>SELECT * FROM table WHERE id IN([?i])
SELECT [?n] FROM table
INSERT INTO table VALUES [(?i,?s,?s,?s)]
UPDATE table SET [?n=?s]
</code>```

As you can see, I use square brackets to designate a repetition. However, I am still not sure if I should use them. First objection is that they will collide with SQL server identifier syntax. Next is rather philosophical one - it is another syntax element and I want to introduce as less changes to the syntax as possible.

Also, this syntax will require much more complicated parsing logic, which I am trying to avoid too. So - another option is just to extend the set of types, either with distinct placeholders like ?k for the list of numbers, ?o for the list of identifiers, of with adding a single=letter modifier to the existing type like ?as (or ?astr or astr:name) is an array of strings, ?an and the like.

There is another option - to detect repetitions automatically. If we have a scalar - format it as a single value. If it's array coming - format as a comma-separated list. However, many people find this approach unacceptable, as it can lead to unpredictable results and erroneous (however still safe) query. I am still in doubts if I may choose this way.

答:
The syntax has to cover three things:

Some way to specify the placeholder type

Some way to specify the placeholder source

Some way to handle arrays

You already have the type-specification covered with the ?type syntax - I'd keep this as is and combine it with elements to handle the other two.

The array handling using [...] (with ... being another placeholder-expression) also looks reasonable.

The key part is how you specify the placeholder source. It may not be immediately obvious looking at the code samples, but there are actually quite a large number of different placeholder sources. Lets go through some examples:

SELECT xyz FROM table WHERE name = ?s AND age > ?i

Assuming $params is the top-level set of parameters, then the ?s placeholder takes $params[0] and the ?i placeholder takes $params[1]. As such, the default-behavior you likely want is that the parameter source is an auto-incrementing zero-based key.

INSERT INTO table VALUES [(?i,?s,?s,?s)]

Here the array for [(?i, ?s, ?s, ?s)] is presumably in $params[0] and if iterated via foreach ($params[0] as $key => $value) then the inner placeholders will be populated from $value[0] to $value[3]. This is consistent with the previous example.

SELECT * FROM table WHERE id IN([?i])

Here we have a problem: Presumably the $params[0] array is supposed to be of the format [$id1, $id2, $id3, ...] rather than [[$id1], [$id2], [$id3], ...]. Thus in this case we want ?i to be $value itself, rather than $value[0] (as the auto-incrementing approach implies)

UPDATE table SET [?n=?s]

Here this problem becomes even more clear. In this case you likely want the array format to be [$name1 => $value1, $name2 => $value2, ...] rather than [[$name1, $value1], [$name2, $value2], ...]. Thus the ?n placeholder needs to bind to $key and ?s to $value.

INSERT INTO table VALUES [(:id, :name)]

Of course you can now do the same thing using named keys. Here :id binds $value['id'] and :name binds $value['name'].

SELECT :cols FROM table WHERE id IN(:ids)

And arrays might also be taken from named parameters. This will need to be handled in some way as well.

This is a rough overview of what you need to be able to handle to fully support arrays.

Here is a possible syntax which covers all possibilities. In the following I'll use $key and $value to denominate the current key/value pair. For the top-level $value will contain the top-level placeholders and $key is not defined.

?type      -- source is implicitly $value[$i] with $i being an auto-incrementing,
           -- zero-based integer. I.e. $value[0], $value[1], $value[2], ...
:name?type -- source is $value['name']
v?type     -- source is $value itself
k?type     -- source is $key itself

[...]      -- source for array is $value[$i], again with auto-incrementing $i
:name[...] -- source is $value['name']
v[...]     -- source is $value itself
k[....]    -- source is $key itself
```
<p>This is how the examples would look like using this syntax:</p>
<ul>
<li><code>SELECT xyz FROM table WHERE name = ?s AND age > ?i</code> (the same)</li>
<li><code>INSERT INTO table VALUES [(?i,?s,?s,?s)]</code> (the same)</li>
<li><code>SELECT * FROM table WHERE id IN([v?i])</code> (need to specify that we want the value)</li>
<li><code>UPDATE table SET [k?n = v?s]</code> (need to specify that we want the key/value)</li>
<li><code>INSERT INTO table VALUES [(:id?i, :name?s)]</code> (added types)</li>
<li><code>SELECT :cols[v?n] FROM table WHERE id IN(:ids[v?i])</code> (added array spec)</li>
</ul>
<p>One thing that isn't covered by these examples is the <code>v[...]</code> syntax. One possible use case is to address all top-level placeholder values as an array:</p>
```query('INSERT INTO table VALUES (v[?s])', 'v1', 'v2', 'v3');
// vs
query('INSERT INTO table VALUES ([?s])', array('v1', 'v2', 'v3'));
```

The k[...] syntax is included for consistency only - it has no practical use and isn't even possible for arrays (only PHP >= 5.5 iterators can have arrays as keys).

Now, this syntax just provides you with all the elements you need to fully handle arrays - the details (like, used characters and order) can likely be improved upon.

At this point one may start wondering whether full array handling is really necessary - you need quite a lot of syntactical elements for it. Maybe a simple ?ai for IN clauses will do?

I think it may make sense to include this kind of syntax, despite the added complexity. It does not add syntactical overhead when not used (only the ?type part is required) and you have the functionality when you need it. In my experience SQL injection vulnerabilities (total noobs notwithstanding) are usually introduced during generation of complex queries, as query generation puts you outside the usual placeholder framework. The best way to prevent this is to make sure that you can even create more complex queries without leaving the framework.

Body:
The syntax has to cover three things:

Some way to specify the placeholder type

Some way to specify the placeholder source

Some way to handle arrays

You already have the type-specification covered with the ?type syntax - I'd keep this as is and combine it with elements to handle the other two.

The array handling using [...] (with ... being another placeholder-expression) also looks reasonable.

The key part is how you specify the placeholder source. It may not be immediately obvious looking at the code samples, but there are actually quite a large number of different placeholder sources. Lets go through some examples:

SELECT xyz FROM table WHERE name = ?s AND age > ?i

Assuming $params is the top-level set of parameters, then the ?s placeholder takes $params[0] and the ?i placeholder takes $params[1]. As such, the default-behavior you likely want is that the parameter source is an auto-incrementing zero-based key.

INSERT INTO table VALUES [(?i,?s,?s,?s)]

Here the array for [(?i, ?s, ?s, ?s)] is presumably in $params[0] and if iterated via foreach ($params[0] as $key => $value) then the inner placeholders will be populated from $value[0] to $value[3]. This is consistent with the previous example.

SELECT * FROM table WHERE id IN([?i])

Here we have a problem: Presumably the $params[0] array is supposed to be of the format [$id1, $id2, $id3, ...] rather than [[$id1], [$id2], [$id3], ...]. Thus in this case we want ?i to be $value itself, rather than $value[0] (as the auto-incrementing approach implies)

UPDATE table SET [?n=?s]

Here this problem becomes even more clear. In this case you likely want the array format to be [$name1 => $value1, $name2 => $value2, ...] rather than [[$name1, $value1], [$name2, $value2], ...]. Thus the ?n placeholder needs to bind to $key and ?s to $value.

INSERT INTO table VALUES [(:id, :name)]

Of course you can now do the same thing using named keys. Here :id binds $value['id'] and :name binds $value['name'].

SELECT :cols FROM table WHERE id IN(:ids)

And arrays might also be taken from named parameters. This will need to be handled in some way as well.

This is a rough overview of what you need to be able to handle to fully support arrays.

Here is a possible syntax which covers all possibilities. In the following I'll use $key and $value to denominate the current key/value pair. For the top-level $value will contain the top-level placeholders and $key is not defined.

?type      -- source is implicitly $value[$i] with $i being an auto-incrementing,
           -- zero-based integer. I.e. $value[0], $value[1], $value[2], ...
:name?type -- source is $value['name']
v?type     -- source is $value itself
k?type     -- source is $key itself

[...]      -- source for array is $value[$i], again with auto-incrementing $i
:name[...] -- source is $value['name']
v[...]     -- source is $value itself
k[....]    -- source is $key itself

This is how the examples would look like using this syntax:

SELECT xyz FROM table WHERE name = ?s AND age > ?i (the same)

INSERT INTO table VALUES [(?i,?s,?s,?s)] (the same)

SELECT * FROM table WHERE id IN([v?i]) (need to specify that we want the value)

UPDATE table SET [k?n = v?s] (need to specify that we want the key/value)

INSERT INTO table VALUES [(:id?i, :name?s)] (added types)

SELECT :cols[v?n] FROM table WHERE id IN(:ids[v?i]) (added array spec)

One thing that isn't covered by these examples is the v[...] syntax. One possible use case is to address all top-level placeholder values as an array:

query('INSERT INTO table VALUES (v[?s])', 'v1', 'v2', 'v3');
// vs
query('INSERT INTO table VALUES ([?s])', array('v1', 'v2', 'v3'));

The k[...] syntax is included for consistency only - it has no practical use and isn't even possible for arrays (only PHP >= 5.5 iterators can have arrays as keys).

Now, this syntax just provides you with all the elements you need to fully handle arrays - the details (like, used characters and order) can likely be improved upon.

At this point one may start wondering whether full array handling is really necessary - you need quite a lot of syntactical elements for it. Maybe a simple ?ai for IN clauses will do?

I think it may make sense to include this kind of syntax, despite the added complexity. It does not add syntactical overhead when not used (only the ?type part is required) and you have the functionality when you need it. In my experience SQL injection vulnerabilities (total noobs notwithstanding) are usually introduced during generation of complex queries, as query generation puts you outside the usual placeholder framework. The best way to prevent this is to make sure that you can even create more complex queries without leaving the framework.


问:
Where should variables be declared
Considering I have a for loop in a method of a class. Should the incremented variable be declared as member of the class, or should it be declared in the method it uses it(or even in the for loop, directly)? While declaring it inside the method seems easier and cleaner, doesn't declaring it at the start of the class makes you have more control over it? Something like declaring it int var_used_for_loop_in_method_x. What is good programming practice?

Note that I'm not asking specifically for the for loop. I am asking if we should try to put most variables as class members as much as possible or not.

答:
Rule of thumb: variables should always be in - or as close as possible to - the scope where they are needed. Another way to phrase it is that variables should be enclosed inside the context in which they make sense and are actually useful.

Most often you will want to declare your incrementing variable along with the for statement. Sometimes you will declare it a bit higher in the hierarchy because you need to know how many occurrences you looped through or at which point the loop was interrupted.

In almost all scenarios, having a loop increment variable declared as a class field is a bad idea. It won't give you any kind of additional "control"; if anything, it will only pollute your class and make it harder to figure out from an outsider's perspective. Plus, if you inadvertently use it in more than one loop, it may even break your code.

UPDATE:

About the latter, as keshlam explains very well in the comments below, a smaller scope will minimize the risk of your variable being modified where you wouldn't expect it. Plus, as he further explains, variables can safely free up used memory when going out of scope. Most modern languages will even do that for you automatically (your mileage may vary).

Also, since you asked what purpose could class-level variables serve, here are two examples in c# :

Property backends

This is likely the most popular use-case.

```<code>public class ConnectionHolder
{
    // ...

    IDbConnection _connection;

    public IDbConnection Connection
    {
        get { return _connection; }
    }

    // ...
}
</code>```

Holder of instance state information

Here we have the property in the above example accessing a factory that will in turn produce an instance of a IDbConnection. The _connectionAccessed boolean variable serves as a flag to tell if an attempt at getting ahold of a connection already has been made.

```<code>public class ConnectionHolder
{
    // ...

    bool _connectionAccessed = false;
    IDbConnection _connection;

    public IDbConnection Connection
    {
        get
        {
            if (!_connectionAccessed)
            {
                _connectionAccessed = true;
                _connection = ConnectionFactory.Create();
            }

            return _connection;
        }
    }

    // ...
}
</code>```

As you can see in the two examples above it makes complete sense for the variables to be declared within full class scope.

I hope you find this information useful.

Title: Where should variables be declared

Body:
Rule of thumb: variables should always be in - or as close as possible to - the scope where they are needed. Another way to phrase it is that variables should be enclosed inside the context in which they make sense and are actually useful.

Most often you will want to declare your incrementing variable along with the for statement. Sometimes you will declare it a bit higher in the hierarchy because you need to know how many occurrences you looped through or at which point the loop was interrupted.

In almost all scenarios, having a loop increment variable declared as a class field is a bad idea. It won't give you any kind of additional "control"; if anything, it will only pollute your class and make it harder to figure out from an outsider's perspective. Plus, if you inadvertently use it in more than one loop, it may even break your code.

UPDATE:

About the latter, as keshlam explains very well in the comments below, a smaller scope will minimize the risk of your variable being modified where you wouldn't expect it. Plus, as he further explains, variables can safely free up used memory when going out of scope. Most modern languages will even do that for you automatically (your mileage may vary).

Also, since you asked what purpose could class-level variables serve, here are two examples in c# :

Property backends

This is likely the most popular use-case.

public class ConnectionHolder
{
    // ...

    IDbConnection _connection;

    public IDbConnection Connection
    {
        get { return _connection; }
    }

    // ...
}

Holder of instance state information

Here we have the property in the above example accessing a factory that will in turn produce an instance of a IDbConnection. The _connectionAccessed boolean variable serves as a flag to tell if an attempt at getting ahold of a connection already has been made.

public class ConnectionHolder
{
    // ...

    bool _connectionAccessed = false;
    IDbConnection _connection;

    public IDbConnection Connection
    {
        get
        {
            if (!_connectionAccessed)
            {
                _connectionAccessed = true;
                _connection = ConnectionFactory.Create();
            }

            return _connection;
        }
    }

    // ...
}

As you can see in the two examples above it makes complete sense for the variables to be declared within full class scope.

I hope you find this information useful.


问:
Solutions to problems that .NET can solve better than Java (or vice-versa)
To me it seems these are two different platforms that address similar enterprise(but not only) problems. I'm interested however in problems that Java can solve better than C#/.NET or C#/.NET can solve better than Java. Leaving aside the 'cost' factor, since that is somehow not an issue for big enterprise companies (the developers probably cost more than the licenses from Microsoft - it's just a thought) and even for small projects there are free/open-source tools for .NET so the cost can be zero for the .NET world as well. With Mono, you can port .NET to Linux and MacOS as well so the benefit that Java had(cross platform) isn't THE decision factor to use Java nowadays..

What real world problems can you think of where .NET would be a much better solution than Java, and vice-versa? I'm only interested in solutions to problems.

答:
For us we can run Java programs on our deployment platform and we cannot run neither .NET nor Mono.

The world is larger than just Windows+Linux+OS X.


问:
Should we include external systems in Class diagram?
I want to draw a class diagram that shows the following for an application:

An external content management system that publishes some news items.

The class that represents the news item in my application.

The question is shall I include the external content management system as a class in my diagram (and maybe give it a different color or add a comment that it is an external component) ?

if the answer is no, what shall I include in the class diagram ? the news item class only ? and how to show the relation between the news item class and the external content management system ?

答:
I work at a Fortune 100 company as a Senior Architect.  We're about as uptight about UML as you find in the industry, and we don't worry about these kinds of things.

Basically, if including an external system (typically using a separate package notation) helps explain something, then include it.  If it is just there for some insignificant corner case that nobody's going to care about, leave it off.

UML exists primarily as a communication tool.  The point is to be able to have diagrams that explain important features of a system.  So, when deciding to include or ignore any feature in any UML diagram, your first question should be:  "Is this thing necessary for describing the important aspects of my system, given this diagram's purpose?"  (Various UML diagrams have different purposes, so something can legitimately be ignored in one, and included in another.)


问:
Understanding and memorizing git rebase parameters
So far the most confusing portion of git is rebasing onto another branch. Specifically, it's the command line arguments that are confusing.

Each time I want to rebase a small piece of one branch onto the tip of another, I have to review the git rebase documentation and it takes me about 5-10 minutes to understand what each of the 3 main arguments should be.

git rebase <upstream> <branch> --onto <newbase>

What is a good rule of thumb to help me memorize what each of these 3 parameters should be set to, given any kind of rebase onto another branch?

Bear in mind I have gone over the git-rebase documentation again, and again, and again, and again (and again), but it's always difficult to understand (like a boring scientific white-paper or something). So at this point I feel I need to involve other people to help me grasp it.

My goal is that I should never have to review the documentation for these basic parameters. I haven't been able to memorize them so far, and I've done a ton of rebases already. So it's a bit unusual that I've been able to memorize every other command and its parameters so far, but not rebase with --onto.

答:
Just a refresher, rebasing is mainly for when you want your commit history to appear linear if two branches have developed independently of one another, basically it rewrites commit history.

the way I like to do it is git rebase --onto <target branch> <start branch> <end branch>

where <target branch> is the branch you are rebasing onto, <start branch> is normally the branch from which <end branch> split and <end branch> is the branch you are rebasing.

if you start with

```<code>A--B--F--G master
    \
     C--D--E feature
</code>```

and do

```<code>git rebase --onto master master feature
</code>```

you will get

```<code>A--B--F--G master
          \
           C'--D'--E' feature
</code>```

another good thing to know is that <target branch> defaults to <start branch> so you can do that same rebase as

```<code>git rebase --onto master feature
</code>```

if you need more help, check out the Rebase without tears guide

Body:
Just a refresher, rebasing is mainly for when you want your commit history to appear linear if two branches have developed independently of one another, basically it rewrites commit history.

the way I like to do it is git rebase --onto <target branch> <start branch> <end branch>

where <target branch> is the branch you are rebasing onto, <start branch> is normally the branch from which <end branch> split and <end branch> is the branch you are rebasing.

if you start with

A--B--F--G master
    \
     C--D--E feature

and do

git rebase --onto master master feature

you will get

A--B--F--G master
          \
           C'--D'--E' feature

another good thing to know is that <target branch> defaults to <start branch> so you can do that same rebase as

git rebase --onto master feature

if you need more help, check out the Rebase without tears guide


答:
If the requirements will change in the future ( which they always do ) you would be best served by having a fairly normalized DB based on Identifier values ( say customer ID , Order ID ..)
By making sure you have a basic sound design to start with you'll be considered a genius when you say " yeah we can do that".</p>


问:
How to document the high-level structure of a Java program?
Background:
My collaborators and I are writing an article for an academic journal.
In the course of our research,
we wrote a simulation program in Java.
We want to make the simulation program freely available for others to use.
We have decided on hosting the code on a GitHub repository.
In order to make it easy for others to use,
we want to write good documentation for our program, including:

Javadocs for each class and method

How to use the code

Describing the high-level structure of the code

My high-level question is:
Could you provide a good example of the words and diagrams
    that can be used to describe the high-level structure of a program?
This includes as sub-questions:

How do we show what classes are contained in which packages?

How do we show what packages depend on other packages?

How do we show how the objects/classes in the program work together?

We have tried to use domain-driven design principles
in the design of my code.
How do we show the correspondence between the objects in the domain
and the particular source code files encoding these objects?
(See my "ubiquitous language" description of the project below.)

What I have done so far

Ubiquitous language

We put a "ubiquitous language" description of the code
in a file ubiquitous-language.md,
contents below.

The purpose of this project is to study how well a replenishment policy
performs in a simple supply chain with a single facility,
under different lead time models, report delays and demand models.

In each period, the following events occur:

If a shipment is scheduled to arrive at the facility at the
current period, then the inventory level of the facility is
incremented by X units.

If the schedule indicates that the current period is a reporting
period, then the facility submits a report to the
supplier.  The supplier may receive the report
instantaneously, or with a delay of several weeks, as specified by
the schedule.

If the supplier has received a report, then based on the
replenishment policy, it will calculate a replenishment
quantity of X units.  A shipment of X units of the product will
be scheduled to arrive after a lead time of l periods.

Customers arrive at the facility and demand X units of the
product.  Any unmet demand is lost.

Source Code Structure

We put an incomplete "high-level" description of the code
in a file structure.md,
contents below.

Package Level Structure

At the highest level, the source code is organized into three packages

com.gly.sfs
The main class with the main method resides in this package.

com.gly.sfs.model
The domain model classes reside in this package.

com.gly.sfs.util
Helper classes reside in this package.

答:
Normally, you'd use UML for the purpose you describe.  UML basically breaks down into two types of diagrams:  structural and behavioral.

Structural diagrams include:  composition, deployment, package, class, object, and component.  Behavioral diagrams include:  sequence, state machine, communication, use case, activity, and interaction overview.

Depending on what you're trying to convey, you pick a few of these diagrams which best represent whatever you're trying to convey, and by so doing you allow the conversation to "move up a level".  Instead of talking about methods, parameters, and code, you're talking about sequence of interactions, or static class dependencies, or whatever diagrams you choose to create.

I've attached an example of a sequence diagram (one of the behavior diagrams).  I personally like the sequence diagram because it's right in the middle of the design artifact process -- roughly an equal number of diagrams depend on it as it expects as input.  I find that the input diagrams are typically "understood" anyway, or the sequence diagram already implies their existence.  However, sometimes I do both static class diagrams and sequence diagrams (one structural and one behavioral diagram).

http://omarfrancisco.com/wp-content/uploads/2011/07/sequencediagram.png

I have never seen this diagram before in my life, but I can tell a number of things about this system.  There are four major components (the nouns in your system -- typically the classes):  View, Controller, Data Proxy, and Data Provider.  The arrows are "behaviors" or method invocations.  A sequence diagram is basically good for showing a single important interaction between a bunch of components.  You have one sequence diagram for each important flow through your system.  I can tell from this particular diagram that "Controller" exposes a method called "phoneIsComplete()", which in turn depends on DataProviderProxy's "lookupPhone()" method, which in turn depends on DataProvider's "lookupPhone()" method.

Now, you might groan and think "uggg... this doesn't give me a big picture of the system -- it's just individual interactions through the system".  Depending on the sophistication of the system, that might be a valid concern (simple systems can definitely get by with just a collection of sequence diagrams).  So, we move over to the structural diagrams and we look at something like a static class diagram:

http://www.f5systems.in/apnashoppe/education//img/chapters/uml_class_diagram.jpg

Class diagrams help us figure out two important things:  cardinality, and class relationship types.  Classes can be related to one another in different ways:  association, aggregation, and composition.  Technically speaking, there's a difference between "static class relationships" and "instance relationships".  However, in practice you see these lines blurred.  The main difference is that static class relationships don't usually include cardinality.  Let's look at the example above and see what we can see.  First, we can see that "Special Order" and "Normal Order" are subtypes of "Orders" (inheritance).  We can also see that one Customer has N Orders (which may be "Normal Orders", "Orders", or "Special Orders") -- the Customer object doesn't really know.  We can also see a number of methods (in the bottom half of each class box) and properties (top half of each class box).

I could keep talking about UML diagrams for a long time, but this is the basics.  Hopefully that helps.

TLDR;  Pick one behavioral and one structural UML diagram, learn how to create it, and you'll accomplish what you're trying to accomplish.


答:
I do this sort of stuff regularly, for a major financial organisation.

I'd say your #2 is almost right, except for the "human, human database" part.  Make it readable, sure, but prioritise PARSEABLE.  Excel is the wrong output format, too, though you could certainly build excel stuff FROM your output format (output CSV, for example, then build on that if you like).

Lets say your records look like this:

S:1
T
COKE
P=20
V=1000

S:2
Q
B=23
S=24
FANTA

S:1
T
FANTA
P=24
V=1000

S:2
Q
B=24
S=26
FANTA

Let's say you want to extract all the Q records, and find the maximum B values, for each brand.  So FANTA=26, based on the above.

First, you need to find the right records.  That's just reading the data and looking for a newline followed by "S:", reading the next line, and reading until the next newline, if that next line was Q.

Then, you split the record by newlines, find the line starting with S=, and parse the rest into a value.  You also need the brand, which is just the fifth field, in your list of elements that were separated by newlines.

Finally, you just need to keep a map of brands, and their maximum values seen so far.  Each time you see a new value for a brand, check if it's higher than the previous value for that brand. If it is, update the value.

The critical part is: when you do this, WRITE ANOTHER SIMPLE, PARSEABLE, TEXT FILE, or again, maybe CSV, so long as your data is simple enough to genuinely map to CSV without data loss.

My output format for this would be as simple as:

FANTA=26

No more, no less.  But sure, swap that = for a comma, and call it CSV if you like.  YAML/JSON are also handy formats, when the need arises.  The point is: keep it as simple as it can possibly be.

Write that data to a file which sits just beside your original input file.

This way, you get new data per day, and it's expanding on the old data, which is in a file right beside that.  So you've added value, but you haven't increased the complexity.

That's a critical difference, from, say, putting all the information behind some database API, or displaying it in some java GUI, which isn't easily accessible to summarise at the end of the year.


问:
Separation of presentation and logic
I'm now writing a program, which will allow processing data expressed in the form of graphs. These graphs will determine workflow of the processing and they are actually an essence of this program (in terms of being the main object being edited by the user).

It is very, very tempting to put all the processing, data containment and presentation in a single control, which will also display these graphs and handle user interaction. From one side it seems to be violation of the presentation/logic rule, but from the other I'm certain I will write surely at least 2x or 3x less code, because I won't have to take care of constant synchronization between data model and the control, which will present this model (+encapsulation, interfaces, proxy classes etc.)

I'm wondering how it is done in editors like Word. Is the data displayed by the control really physically separated from the presenter or are they combined? If you use the Word document control in your program, you ask the control to perform operations on text, what would suggest, that there is no separation (but we don't know how does it work under the hood).

So the question: is separation between data presentation and logic worth it even if it requires like 2x or 3x more code to keep everything consistent and synchronized? (yes, I mean 2x or 3x).

I've described the situation in more detail in the next question: https://stackoverflow.com/questions/22373108/how-to-separate-logic-from-presentation

答:
So the question: is separation between data presentation and logic worth it even if it requires like 2x or 3x more code to keep everything consistent and synchronized? (yes, I mean 2x or 3x).

I would strongly recommend separating out the layers. There are a few reasons:

Controls often start simple then become more complex over time.

Controls may be reused in other areas of an application or other applications.

If controls need to interact with one another, having events isolated will greatly simplify code.

OwnerDisplayName: Spook

Title: Separation of presentation and logic

OwnerDisplayName: Stuart Thompson