问:
Meaning of directories names
I was looking for a dictionary where are described the meanings and purposes of each directory name used in softwares file trees.

I can't find anything except for the Linux FHS, but that is restricted to GNU/Linux OS.

So I would like to ask you something to understand the meaning of the following folders:

```<code>/controllers
/models
/vendor
/src
</code>```

This is what I've understood so far:

/controllers <s>is where I should put the files that have the purpose of control other files. For example in controllers I could have a PHP file that load a file to call MySQL queries, then one that parse the queries to structure an array, and then one that calls the template manager.</s>

/models I've no idea of what is intended for...

/vendor is where are located external dependencies needed by the software.

/src is where the source files are located.

My doubts are:

What is the /models folder?

If for example I include in my project, Mustache.php, I will have Mustache located in /src/Mustache.

But it also adds some dependencies in the /vendor folder.

The problem is, in my project, even Mustache is a "vendor" thing (I guess), so shouldn't it moved to /vendor?

If I'm writing in PHP, HTML, JS and CSS. Every file I use for the production will be also the source file, so why shouldn't I put everything in the /src folder and keep out maybe only the minified .js, .css and .html?

答:
Where exactly did you find these folders? Details of such a structure often depend on the project, programming language and web framework in use. This one looks like a rather typical MVC structure (model, view, controller) as often used in web projects. Though missing the view part (unless this is /src). In any case this has nothing to do with the Linux FSH which only defines the OS level and not single projects.

You should start reading a bit about the MVC model. The controller should normally just take an incoming request for some specific URL and the get data from the model that is needed by the view to render the response. So the controller should do as less work as possible.

The model is where all database and business logic resides.

Vendor should in most cases hold external plugins and libraries you include in your project. If you write plugins yourself then you may put them there too. Other frameworks will have a dedicated /lib folder for such things (Maybe that's /src in your case?)

I don't know exactly what /src should be for. Obviously this should mean source, but I come from a Ruby on Rails background.

For /lib: you often need some additional libraries you write for some tasks that do not exactly fit the mvc model, say you need some helper classes that do things like converting data to XML or generate statistical data and graphs or some database driver for some specific database your framework doesn't support natively. All such things would go into the /lib folder. But you are free to add more like Rails for example has folders like /script, /helpers, /mailers, /config and many more. And of course subfolders, like you would most of the time want to keep .js, .html and .css separated, since these become a lot of files in larger projects (again Rails as example would in most cases keep the views html files in subfolders named similar to the controllers, since there often is a direct relation between controllers and the views they render, so your customers controller will need all the html files used to render a customers information)

As said, all depends on your tools. Especially web frameworks often define very clear structures and depend on the right files being in the right place. So if you don't use pure PHP but a framework like CodeIgniter you should consult the frameworks documentation.

Title: Meaning of directories names


答:
When developing a project, I think two main principles can be applied to naming folders/directories:

Choose semantically correct and descriptive name

Choose a popular/established name used for a directory with certain purpose

There are many established naming conventions. From the examples you brought, I've met src used in Java projects for naming the head directory containing source code. models and controllers are commonly used in MVC (model-view-controller) pattern.

That said, to understand the names you need to understand the context they're used in _ language, framework, type of project, etc.

ContentLicense: CC BY-SA 3.0

Title: Meaning of directories names

Body:
I was looking for a dictionary where are described the meanings and purposes of each directory name used in softwares file trees.

I can't find anything except for the Linux FHS, but that is restricted to GNU/Linux OS.

So I would like to ask you something to understand the meaning of the following folders:

```<code>/controllers
/models
/vendor
/src
</code>```

This is what I've understood so far:

/controllers <s>is where I should put the files that have the purpose of control other files. For example in controllers I could have a PHP file that load a file to call MySQL queries, then one that parse the queries to structure an array, and then one that calls the template manager.</s>

/models I've no idea of what is intended for...

/vendor is where are located external dependencies needed by the software.

/src is where the source files are located.

My doubts are:

What is the /models folder?

If for example I include in my project, Mustache.php, I will have Mustache located in /src/Mustache.

But it also adds some dependencies in the /vendor folder.

The problem is, in my project, even Mustache is a "vendor" thing (I guess), so shouldn't it moved to /vendor?

If I'm writing in PHP, HTML, JS and CSS. Every file I use for the production will be also the source file, so why shouldn't I put everything in the /src folder and keep out maybe only the minified .js, .css and .html?


问:
Consequences of "naïve" vs "naive"?
While using IE autocorrect "naive" got transformed to "naïve"!
My regional settings are Au English, from a Unicode search point of view the two are nothing alike. I am not even sure whether there are other characters that are being replaced, but from a programmers point of view what are the consequences and remedies in such cases? In SQL is there a way to return results containing both "naïve" and "naive"? (without hardcoding or explicit programming of course).

Are there other instances of automatic transliteration that one should be aware of? Or is there a method to handle such sameness of characters in other languages? e.g. umlats in German and lack/inclusion of vowels in Arabic script based words.

Thanks for any observations on this matter

答:
As Pete's answer points out, you can address this using "accent-insensitive" collation rules.

But I think that's only a band-aid.

You could say that 'naive' and 'naïve' are really just alternative (arguably correct) spellings of the same word.  In the same ilk, what about 'colour' versus 'color'?  And what about accidental ... or deliberate ... misspellings and typing errors?

The big picture here is that if you are going to pick apart text produced (at some point) by humans, your code has to deal with all sorts of variability.

If there is a general technique for solving this, it is probably to normalize your text to standard spellings and orthography (broadly defined) before you store it in the database.  And consider using a free-text search engine rather than a regular database.

Title: Consequences of "naïve" vs "naive"?


问:
Internal-use websites: Is there a compelling case against SQLite?
Many web frameworks, such as Flask or Django use SQLite as their default database.  SQLite is compelling because it's included in python, and administrative overhead is pretty low.

However, most high traffic public production sites wind up using a heavier database: mySQL, Oracle, or postgresql.

The questions:

Assume:

Site traffic is moderate, and concurrent read/write access to the database will happen

We will use SQLAlchemy with SQLite write locks (although this comment makes me a little nervous)

The database will contain perhaps 60,000 records

Data structures do not require advanced features found in heavier databases

Is there ever a compelling case against SQLite concurrency for websites that  serve as moderate-traffic internal corporate tools?  If so, what conditions will cause SQLite to have concurrency problems?

I'm looking for known specific root causes, instead of general fear / unsubstantiated finger pointing.

答:
I recommend reading the official answer to your question, Appropriate Uses For SQLite.  Specifically, the "Situations Where Another RDBMS May Work Better" warns that SQLite does not support concurrent writing:

SQLite supports an unlimited number of simultaneous readers, but it
  will only allow one writer at any instant in time. For many
  situations, this is not a problem. Each application does its database
  work quickly and moves on, and no lock lasts for more than a few dozen
  milliseconds. But there are some applications that require more
  concurrency, and those applications may need to seek a different
  solution.

From an appropriateness perspective, I tend to view SQLite as a very sophisticated file format that supports SQL queries.  I would tend to avoid SQLite if I wanted to separate my database from my web application, as it is not optimized for this case.  In short, SQLite is insufficiently scalable for use in some scenarios, so people running websites who hope to someday become popular may be better off starting with something scalable, rather than going with SQLite and later being forced to switch.

All that being said, SQLite is probably fine for most internal websites; typically internal websites don't require the same level of concurrency and scalability.


问:
can you have too many dto/bo - mapping method
I have a windows service, 2 web services and a web interface that need to follow the same path (data wise).

So I came up with two ways of creating my solution.

My concern is the fact that the UI/WS/etc will have their own kind of DTO (let's say the model in ASP.Net MVC) that should be mapped to a DTO so the SL can then map it to a BO then mapping it to the proper EF6 DTO so that I can save it in a database.

So I'm thinking of doing it this way

to remove one level of mapping.

Which one should I take? Or is there a 3rd solution?

答: My instinct here is that the Service Layer doesn't need to know about DTOs, so based on that I'd say your second architecture makes more sense. Some of your presentation layer might need to map into specialised objects such as the DTOs and view models, but it may also be appropriate to use naked BOs for others if the data are already in a usable form.</p>


问:
Why did Java make package access default?
I'm asking this question because I believe they did it for a very good reason and that most people do not use it properly, well from my experience in industry so far anyway.
But if my theory is true then I'm not sure why they included the private access modifier...?

I believe that if default access is properly used it provides enhanced testability whilst maintaining encapsulation. And it also renders the private access modifier redundant.

The default access modifier can be used to provide the same affect by using a unique package for methods that need to be hidden from the rest of the world, and it does this without compromising testability, as packages in a test folder, with the same are able to access all the default methods declared in a source folder.

I believe this is why Java uses package access as 'default'. But I'm not sure why they also included private access, I'm sure there is a valid use case...

答:
I guess they had a good idea of what an average programmer would do. And by average programmer I mean one who is not really good at programming, but gets the job anyway because there are not enough good ones and they are expensive.

If they made "public" access the default one, most programmers would never bother to use anything else. The result would be a lot of spaghetti code everywhere. (Because if you are technically allowed to call anything from anywhere, why ever bother to encapsulate some logic within a method?)

Making "private" the default access would only be slightly better. Most beginning programmers would simply invent (and share on their blogs) a rule of thumb that "you need to write 'public' everywhere", and then they would complain why Java is so bad that it forces them to write "public" everywhere. And they would also produce a lot of spaghetti code.

The package access is something that allows programmers to use their sloppy programming techniques while writing code within one package, but then they have to reconsider it when making more packages. It is a compromise between good business practices and the ugly reality. Like: write some spaghetti code, if you insist, but please leave the ugly mess within the package; at least create some nicer interfaces among the packages.

Probably there are other reasons, too, but I wouldn't underestimate this one.


答:
Typography is another frequent source of character substitution. Certain two-letter combinations may be replaced by ligatures during printing (e.g. ae might become æ), fractions expressed in text might be replaced with single characters, and symbols that are often mimicked in text may be replaced with dedicated characters (e.g. (c) becomes ©).

Such transformations are often performed when documents are being prepared for printing, but printing doesn't necessarily mean toner on paper. PDF files are typically produced by a printing-like process, so if PDF files are an input to your process, you may need to consider alternative forms for your data. For example, if you're searching for data in a PDF file, you need to be aware of the ways that text can change.

One way to manage this sort of thing is to convert all data to a canonical form before using it. Choose a form that makes sense for your project. You might decide to exclude ligatures but keep accents and symbols where possible. Then create a set of filters that implement your rules and use them to canonicalize all data coming into the system. This lets you do a single search for words like naïve instead of having to search for both naïve and naive.

The other way to manage it is to use unmodified data and try to deal with all the possible variations that might occur. If you don't have control over the data (e.g. you're searching through data on someone else's server) this may be the only reasonable option. Regular expressions can help here -- you can search for na[iï]ve.

Title: Consequences of "naïve" vs "naive"?

Body:
While using IE autocorrect "naive" got transformed to "naïve"!
My regional settings are Au English, from a Unicode search point of view the two are nothing alike. I am not even sure whether there are other characters that are being replaced, but from a programmers point of view what are the consequences and remedies in such cases? In SQL is there a way to return results containing both "naïve" and "naive"? (without hardcoding or explicit programming of course).

Are there other instances of automatic transliteration that one should be aware of? Or is there a method to handle such sameness of characters in other languages? e.g. umlats in German and lack/inclusion of vowels in Arabic script based words.

Thanks for any observations on this matter


答:
Default access does not render the private access modifier redundant.

Language designers position on that is reflected in official tutorial - Controlling Access to Members of a Class and it's pretty clear (for your convenience, relevant statement in the quote made bold):

Tips on Choosing an Access Level:

If other programmers use your class, you want to ensure that errors from misuse cannot happen. Access levels can help you do this.

Use the most restrictive access level that makes sense for a particular member. Use private unless you have a good reason not to.

Avoid public fields except for constants. (Many of the examples in the tutorial use public fields. This may help to illustrate some points concisely, but is not recommended for production code.) Public fields tend to link you to a particular implementation and limit your flexibility in changing your code.

Your appeal to testability as justification for completely dropping private modifier is wrong, as evidenced eg by the answers in New to TDD. Should I avoid private methods now?

Of course you can have private methods, and of course you can test them.

Either there is some way to get the private method to run, in which case you can test it that way, or there is no way to get the private to run, in which case: why the heck are you trying to test it, just delete the damn thing...

Position of language designers on the purpose and usage of package level access is explained in another official tutorial, Creating and Using Packages and it has nothing in common with the idea of dropping private modifiers (for your convenience, relevant statement in the quote made bold):

You should bundle these classes and the interface in a package for several reasons, including the following:

You and other programmers can easily determine that these types are related...

You can allow types within the package to have unrestricted access to one another yet still restrict access for types outside the package...

<rant "I think I heard enough whining. Guess it's about time to say loud and clear...">

Private methods are beneficial to unit testing.

Note below assumes that you are familiar with code coverage. If not, take a time to learn, since it's quite useful to those interested in unit testing and in testing at all.

All right, so I've got that private method and unit tests, and coverage analysis telling me that there's a gap, my private method isn't covered by tests. Now...

What do I gain from keeping it private

Since method is private, the only way to proceed is to study the code to learn how it is used through non-private API. Typically, such a study reveals that reason for the gap is that particular usage scenario is missing in tests.

```<code>    void nonPrivateMethod(boolean condition) {
        if (condition) {
            privateMethod();
        }
        // other code...
    }

    // unit tests don't invoke nonPrivateMethod(true)
    //   => privateMethod isn't covered.
</code>```

For the sake of completeness, other (less frequent) reasons for such coverage gaps could be bugs in specification / design. I won't dive deep into these here, to keep things simple; suffice to say that if you weaken access limitation "just to make method testable", you'll miss a chance to learn that these bugs exist at all.

Fine, to fix the gap, I add a unit test for missing scenario, repeat coverage analysis and verify that gap is gone. What do I have now? I've got as new unit test for specific usage of non-private API.

New test ensures that expected behavior for this usage won't change without a notice since if it changes, test will fail.

An outside reader may look into this test and learn how it is supposed to use and behave (here, outside reader includes my future self, since I tend to forget the code a month or two after I'm done with it).

New test is tolerant to refactoring (do I refactor private methods? you bet!) Whatever I do to privateMethod, I'll always want to test nonPrivateMethod(true). No matter what I do to privateMethod, there will be no need to modify test because method isn't directly invoked.

Not bad? You bet.

What do I loose from weakening access limitation

Now imagine that instead of above, I simply weaken access limitation. I skip the study of the code that uses the method and proceed straight with test that invokes my exPrivateMethod. Great? Not!

Do I gain a test for specific usage of non-private API mentioned above? No: there was no test for nonPrivateMethod(true) before, and there is no such test now.

Do outside readers get a chance to better understand usage of the class? No. "- Hey what's the purpose of the method tested here? - Forget it, it's strictly for internal use. - Oops."

Is it tolerant to refactoring? No way: whatever I change in exPrivateMethod, will likely break the test. Rename, merge into some other method, change arguments and test will just stop compiling. Headache? You bet!

Summing up, sticking with private method brings me a useful, reliable enhancement in unit tests. In contrast, weakening access limitations "for testability" only gives me an obscure, hard to understand piece of test code, which is additionally at permanent risk of being broken by any minor refactoring; frankly what I get looks suspiciously like technical debt.

</rant>

Title: Why did Java make package access default?

Body:
I'm asking this question because I believe they did it for a very good reason and that most people do not use it properly, well from my experience in industry so far anyway.
But if my theory is true then I'm not sure why they included the private access modifier...?

I believe that if default access is properly used it provides enhanced testability whilst maintaining encapsulation. And it also renders the private access modifier redundant.

The default access modifier can be used to provide the same affect by using a unique package for methods that need to be hidden from the rest of the world, and it does this without compromising testability, as packages in a test folder, with the same are able to access all the default methods declared in a source folder.

I believe this is why Java uses package access as 'default'. But I'm not sure why they also included private access, I'm sure there is a valid use case...

Body:
Default access does not render the private access modifier redundant.

Language designers position on that is reflected in official tutorial - Controlling Access to Members of a Class and it's pretty clear (for your convenience, relevant statement in the quote made bold):

Tips on Choosing an Access Level:

If other programmers use your class, you want to ensure that errors from misuse cannot happen. Access levels can help you do this.

Use the most restrictive access level that makes sense for a particular member. Use private unless you have a good reason not to.

Avoid public fields except for constants. (Many of the examples in the tutorial use public fields. This may help to illustrate some points concisely, but is not recommended for production code.) Public fields tend to link you to a particular implementation and limit your flexibility in changing your code.

Your appeal to testability as justification for completely dropping private modifier is wrong, as evidenced eg by the answers in New to TDD. Should I avoid private methods now?

Of course you can have private methods, and of course you can test them.

Either there is some way to get the private method to run, in which case you can test it that way, or there is no way to get the private to run, in which case: why the heck are you trying to test it, just delete the damn thing...

Position of language designers on the purpose and usage of package level access is explained in another official tutorial, Creating and Using Packages and it has nothing in common with the idea of dropping private modifiers (for your convenience, relevant statement in the quote made bold):

You should bundle these classes and the interface in a package for several reasons, including the following:

You and other programmers can easily determine that these types are related...

You can allow types within the package to have unrestricted access to one another yet still restrict access for types outside the package...

<rant "I think I heard enough whining. Guess it's about time to say loud and clear...">

Private methods are beneficial to unit testing.

Note below assumes that you are familiar with code coverage. If not, take a time to learn, since it's quite useful to those interested in unit testing and in testing at all.

All right, so I've got that private method and unit tests, and coverage analysis telling me that there's a gap, my private method isn't covered by tests. Now...

What do I gain from keeping it private

Since method is private, the only way to proceed is to study the code to learn how it is used through non-private API. Typically, such a study reveals that reason for the gap is that particular usage scenario is missing in tests.

    void nonPrivateMethod(boolean condition) {
        if (condition) {
            privateMethod();
        }
        // other code...
    }

    // unit tests don't invoke nonPrivateMethod(true)
    //   => privateMethod isn't covered.

For the sake of completeness, other (less frequent) reasons for such coverage gaps could be bugs in specification / design. I won't dive deep into these here, to keep things simple; suffice to say that if you weaken access limitation "just to make method testable", you'll miss a chance to learn that these bugs exist at all.

Fine, to fix the gap, I add a unit test for missing scenario, repeat coverage analysis and verify that gap is gone. What do I have now? I've got as new unit test for specific usage of non-private API.

New test ensures that expected behavior for this usage won't change without a notice since if it changes, test will fail.

An outside reader may look into this test and learn how it is supposed to use and behave (here, outside reader includes my future self, since I tend to forget the code a month or two after I'm done with it).

New test is tolerant to refactoring (do I refactor private methods? you bet!) Whatever I do to privateMethod, I'll always want to test nonPrivateMethod(true). No matter what I do to privateMethod, there will be no need to modify test because method isn't directly invoked.

Not bad? You bet.

What do I loose from weakening access limitation

Now imagine that instead of above, I simply weaken access limitation. I skip the study of the code that uses the method and proceed straight with test that invokes my exPrivateMethod. Great? Not!

Do I gain a test for specific usage of non-private API mentioned above? No: there was no test for nonPrivateMethod(true) before, and there is no such test now.

Do outside readers get a chance to better understand usage of the class? No. "- Hey what's the purpose of the method tested here? - Forget it, it's strictly for internal use. - Oops."

Is it tolerant to refactoring? No way: whatever I change in exPrivateMethod, will likely break the test. Rename, merge into some other method, change arguments and test will just stop compiling. Headache? You bet!

Summing up, sticking with private method brings me a useful, reliable enhancement in unit tests. In contrast, weakening access limitations "for testability" only gives me an obscure, hard to understand piece of test code, which is additionally at permanent risk of being broken by any minor refactoring; frankly what I get looks suspiciously like technical debt.

</rant>


问:
Modularity and "encapsulation" in C
This applies to C (and probably to any other similar non-object oriented language). If I have a central data store and potentially concurrent access there are two ways I can see of protecting it.

Let's say I have a data store with a few data elements...

```<code>struct MyStore
{
    int data1, data2, data3, ...., dataN;
} store[M];
</code>```

In this example the data types are the same but let's imagine this applies to something a bit more varied with different types etc... this is just to keep the question simple.

To grant other users access to the data within I could do a few things.

Could provide critical region functions and rely on the caller to get the protection correct.

I could provide a setter and getter function for each data item type in the store and manage the critical regions within the module and protect the user from having to deal with any logic.

My trouble with the first method is that the burden is placed on the caller.

My trouble with the second, at least in C, is that firstly I end up writing a whole load of boiler plate accessors and secondly more complex stuff like test-and-set or needing to hold a lock on the data whilst doing several operations becomes messy. E.g. for method 2 I need

```<code>int GetData1(unsigned int index) {
    int data;

    ENTER_CR();
    data = store[index].data1;
    LEAVE_CR();

    return data;
}

...
...

int GetDataN(unsigned int index) {
    int data;

    ENTER_CR();
    data = store[index].dataN;
    LEAVE_CR();

    return data;
}
</code>```

And the same for all the setters. And then what if I want to set multiple items atomically? Gets hard!

How to get some of the benefits of modularity and encapsulation but still have a flexible interface?

答:
When providing a thread-safe interface (with or with OOP) you need to make sure that your operations are at the level you want to be atomic. If setting or getting a single field is the level of atomic operation you want to support, then option 1 works. (On the other hand, getting and setting int's is atomic anyways)

The reality probably is that a simple data object isn't the correct place in a design to provide thread safety, because as you noted you really do not know what the "real" operations the data is being used for are. You can still encapsulate thread safety, but it needs to be where you are doing something, not just storing something.

Title: Modularity and "encapsulation" in C


答:
I believe that if default access is properly used it provides enhanced testability whilst maintaining encapsulation. And it also renders the private access modifier redundant.

There are situations where one would want two separate classes that are more tightly bound than exposing everything with public.  This has similar ideas of 'friends' in C++ where another class that is declared as a 'friend' of another can access their private members.

If you look into the innards of classes such as BigInteger you will find a number of package default protection on fields and methods (everything that is blue triangle in the list).  This allows other classes in the java.math package to have more optimal access to their innards for specific operations (you can find these methods called in BigDecimal - BigDecimal is backed by a BigInteger and saves reimplementing BigInteger again.  That these are package level isn't an issue for protection because java.math is a sealed package and no other classes can be added to it.

On the other hand, there are many things that are indeed private, as they should be. Most packages aren't sealed.  Without private, your co-worker could put another class in that package and access the (no longer) private field and break encapsulation.

Of note, unit testing wasn't something that was thought of back when the protection scopes were being constructed.  JUnit (the XUnit testing framework for Java) wasn't conceived of until 1997 (one telling of the story of that can be read at http://www.martinfowler.com/bliki/Xunit.html ).  The Alpha and Beta versions of the JDK were in 1995 and JDK 1.0 was in 1996, though the protection levels didn't really get nailed down until JDK 1.0.2 (prior to that you could have a private protected protection level).

Some would argue that the default shouldn't be package level, but private.  Others argue that there shouldn't be a default protection but everything should be explicitly stated - some followers of this will write code such as:

```<code>public class Foo {
    /* package */ int bar = 42;
    ...
}
</code>```

Note the comment there.

The real reason why the package level protection is the default is likely lost to the design notes of Java (I've been digging and can't find any why articles, lots of people explaining the difference, but none saying "this is the reason").

So I'll take a guess.  And that's all it is - a guess.

First off, people were still trying to figure out language design. Languages since then have learned from Java's mistakes and successes.  This could be listed as a mistake not to have something that needs to be defined for all fields.

The designers saw an occasional need for a 'friend' relationship of C++.

The designers wanted explicit statements for public, and private as these have the biggest impacts on access.

Thus, private isn't default and well, everything else fell into place.  The default scope was left as default.  It may have been the first scope that was created and in the interest of rigorous backwards compatibility with older code, was left that way.

As I said, these are all a guess.

Body:
I believe that if default access is properly used it provides enhanced testability whilst maintaining encapsulation. And it also renders the private access modifier redundant.

There are situations where one would want two separate classes that are more tightly bound than exposing everything with public.  This has similar ideas of 'friends' in C++ where another class that is declared as a 'friend' of another can access their private members.

If you look into the innards of classes such as BigInteger you will find a number of package default protection on fields and methods (everything that is blue triangle in the list).  This allows other classes in the java.math package to have more optimal access to their innards for specific operations (you can find these methods called in BigDecimal - BigDecimal is backed by a BigInteger and saves reimplementing BigInteger again.  That these are package level isn't an issue for protection because java.math is a sealed package and no other classes can be added to it.

On the other hand, there are many things that are indeed private, as they should be. Most packages aren't sealed.  Without private, your co-worker could put another class in that package and access the (no longer) private field and break encapsulation.

Of note, unit testing wasn't something that was thought of back when the protection scopes were being constructed.  JUnit (the XUnit testing framework for Java) wasn't conceived of until 1997 (one telling of the story of that can be read at http://www.martinfowler.com/bliki/Xunit.html ).  The Alpha and Beta versions of the JDK were in 1995 and JDK 1.0 was in 1996, though the protection levels didn't really get nailed down until JDK 1.0.2 (prior to that you could have a private protected protection level).

Some would argue that the default shouldn't be package level, but private.  Others argue that there shouldn't be a default protection but everything should be explicitly stated - some followers of this will write code such as:

public class Foo {
    /* package */ int bar = 42;
    ...
}

Note the comment there.

The real reason why the package level protection is the default is likely lost to the design notes of Java (I've been digging and can't find any why articles, lots of people explaining the difference, but none saying "this is the reason").

So I'll take a guess.  And that's all it is - a guess.

First off, people were still trying to figure out language design. Languages since then have learned from Java's mistakes and successes.  This could be listed as a mistake not to have something that needs to be defined for all fields.

The designers saw an occasional need for a 'friend' relationship of C++.

The designers wanted explicit statements for public, and private as these have the biggest impacts on access.

Thus, private isn't default and well, everything else fell into place.  The default scope was left as default.  It may have been the first scope that was created and in the interest of rigorous backwards compatibility with older code, was left that way.

As I said, these are all a guess.


答:
You can do in C everything you'd do in another language to make a clean interface - you just have to do it with less language support.

if you want to avoid boilerplate accessors, store all your simple types in a union: then you have a single access by enumerated field ID (ie, an index into an array of unions), and the caller can worry about what type each field is

```<code>struct MyStore;
union Atom {
    int i;
    double d;
    /* any other types */
};

/* access any type by index */
union Atom *field(struct MyStore *, int id);
</code>```

you obviously lose type-safety guarantees that other languages might provide, and client errors here can be nasty, especially if one of the values in your union is a pointer

you can make this a discriminated union if you want more safety, and don't mind checking the type tag by hand

if you want to bundle multiple operations into an atomic event, you can do that:

```<code>struct MyStore;
struct BatchOperation;

struct BatchOperation *startBatch(struct MyStore*);
void endBatch(struct BatchOperation*);

/* force client to call startBatch before accessing */
union Atom *field(struct BatchOperation *, int id);
</code>```

here, starting the batch operation would lock your store, and ending it would release the lock.

again, you don't get any automatic management of the BatchOperation lifetime, so the client code must end the batch or cause a deadlock

PS. Note the opaque types used above: only the union and the public functions are fully visible to client code. This really is encapsulation, with no scare quotes required.

Title: Modularity and "encapsulation" in C

Body:
This applies to C (and probably to any other similar non-object oriented language). If I have a central data store and potentially concurrent access there are two ways I can see of protecting it.

Let's say I have a data store with a few data elements...

```<code>struct MyStore
{
    int data1, data2, data3, ...., dataN;
} store[M];
</code>```

In this example the data types are the same but let's imagine this applies to something a bit more varied with different types etc... this is just to keep the question simple.

To grant other users access to the data within I could do a few things.

Could provide critical region functions and rely on the caller to get the protection correct.

I could provide a setter and getter function for each data item type in the store and manage the critical regions within the module and protect the user from having to deal with any logic.

My trouble with the first method is that the burden is placed on the caller.

My trouble with the second, at least in C, is that firstly I end up writing a whole load of boiler plate accessors and secondly more complex stuff like test-and-set or needing to hold a lock on the data whilst doing several operations becomes messy. E.g. for method 2 I need

```<code>int GetData1(unsigned int index) {
    int data;

    ENTER_CR();
    data = store[index].data1;
    LEAVE_CR();

    return data;
}

...
...

int GetDataN(unsigned int index) {
    int data;

    ENTER_CR();
    data = store[index].dataN;
    LEAVE_CR();

    return data;
}
</code>```

And the same for all the setters. And then what if I want to set multiple items atomically? Gets hard!

How to get some of the benefits of modularity and encapsulation but still have a flexible interface?

Body:
You can do in C everything you'd do in another language to make a clean interface - you just have to do it with less language support.

if you want to avoid boilerplate accessors, store all your simple types in a union: then you have a single access by enumerated field ID (ie, an index into an array of unions), and the caller can worry about what type each field is

struct MyStore;
union Atom {
    int i;
    double d;
    /* any other types */
};

/* access any type by index */
union Atom *field(struct MyStore *, int id);

you obviously lose type-safety guarantees that other languages might provide, and client errors here can be nasty, especially if one of the values in your union is a pointer

you can make this a discriminated union if you want more safety, and don't mind checking the type tag by hand

if you want to bundle multiple operations into an atomic event, you can do that:

struct MyStore;
struct BatchOperation;

struct BatchOperation *startBatch(struct MyStore*);
void endBatch(struct BatchOperation*);

/* force client to call startBatch before accessing */
union Atom *field(struct BatchOperation *, int id);

here, starting the batch operation would lock your store, and ending it would release the lock.

again, you don't get any automatic management of the BatchOperation lifetime, so the client code must end the batch or cause a deadlock

PS. Note the opaque types used above: only the union and the public functions are fully visible to client code. This really is encapsulation, with no scare quotes required.


问:
Best place for a factory interface
What's the best place for a factory interface to create an instance of another interface?

OptionA: a separate class

```<code>public interface InterAFactory {
    InterA createInterA();
}

public interface InterA {
    void doStuff();
}
</code>```

OptionB: a subclass

```<code>public interface InterA {
    public interface Factory {
        InterA createInterA();
    }

    void doStuff();
}
</code>```

I notice that guava has tended to use B for the immutable collections, but that's for builders, which are slightly different to factories. I also tend towards optionB, as  it reduces the number of top-level classes in the package, and it strongly associates the factory with the thing it creates. However, implementations will not be bound or affected by this, and it will make implementations of the factory slightly more verbose. Thoughts?

答:
My personal taste is to use a variation of (a) with generics:

OptionA*: a separate class with generics

```<code>public interface Factory<T> {
    T create();
}
</code>```

So you have only one factory interface for many different types. This is not possible with (b).

I use this in c#/dotnet for a repository factory for different item-types. In java it should be similar.

Title: Best place for a factory interface

Body:
My personal taste is to use a variation of (a) with generics:

OptionA*: a separate class with generics

public interface Factory<T> {
    T create();
}

So you have only one factory interface for many different types. This is not possible with (b).

I use this in c#/dotnet for a repository factory for different item-types. In java it should be similar.


问:
How can I implement a modular "save" function for a game?
I have to implement a method to save my game in such a way that I can change the storage medium with the change of only a single variable.

Ideally I'd use an interface to designate the required method signatures and implement that interface with a different concrete class for each medium. For example, one for database, one for xml, possibly one for serialized objects. How exactly I initiate the save function?

For example, if I have a Class of type Persistence called PersistToXML, which is instantiated to some variable somewhere upon launching the game, how best should I implement it so that I can save my relevant objects as needed?

I'm hesitant to use a Singleton due to all the bad reviews I read about it, and I don't really want to have to pass this object around to every class just in case I need to save something.

答:
I would use something like the Factory Pattern. It would return the concrete implementation of the persistence method you require.

```<code>public class Program
{
    public void SaveGame()
    {
        var gameSaveFormat = ConfigurationManager.AppSettings["gameSaveFormat"];

        var persistence = PersistenceFactory.GetSaveMethod(gameSaveFormat);
        persistence.SaveGame();
    }
}

public interface IPersistence
{
    void SaveGame();
}

public abstract class Persistence : IPersistence
{

    public abstract void SaveGame();
}

public class SaveToDatabasePersistence : Persistence
{

    public override void SaveGame()
    {
        //Implement SaveToDB
    }
}

public class SaveToXmlPersistence : Persistence
{

    public override void SaveGame()
    {
        //Implement SaveToXML File
    }
}

public static class PersistenceFactory
{
    public static IPersistence GetSaveMethod(string saveMethod)
    {
        switch (saveMethod)
        {
            case "Xml":
                return new SaveToXmlPersistence();
                break;
            case "DB":
                return new SaveToDatabasePersistence();
                break;
            default:
                throw new Exception(string.Format("Unknown Save Method. {0}", saveMethod));
        }
    }
}
</code>```

The GetSaveMethod would accept a string that would define the concrete type that you wish to return.

The Persistence abstract class is optional. You should use it if you require common functionality between concrete implementations. If you choose not to use it, each concrete type should implement the interface directly.

You haven't specified what language you are using, but in .NET you can use the ConfigurationManager class to read the persistence method from a configuration file.

Lastly

I'm hesitant to use a Singleton due to all the bad reviews I read about it, and I don't really want to have to pass this object around to every class just in case I need to save something.

doesn't quite make sense. A Singleton class is called when necessary. An object being passed to every class just in case you need to use it, is certainly an incorrect implementation of that pattern.

```<code>public void SaveGame()
{
    var persitanceMethod = MySingleton.GetInstance().PersitanceMethod;

    var persistence = PersistenceFactory.GetSaveMethod(persitanceMethod);
    persistence.SaveGame();
}
</code>```

The above code would be an example (from my head) of how you would call a singleton class to retrieve a property from it.

Update

```<code>public class Program
{
    private readonly IPersistence _persistence;
    public Program(IPersistence persistence)
    {
        _persistence = persistence;
    }

    public void SaveGame()
    {
         var persistenceObject = PersistenceFactory.GetSaveMethod(_persistence.GameSaveFormat);
         persistenceObject.SaveGame();
    }
</code>```

Body:
I would use something like the Factory Pattern. It would return the concrete implementation of the persistence method you require.

public class Program
{
    public void SaveGame()
    {
        var gameSaveFormat = ConfigurationManager.AppSettings["gameSaveFormat"];

        var persistence = PersistenceFactory.GetSaveMethod(gameSaveFormat);
        persistence.SaveGame();
    }
}

public interface IPersistence
{
    void SaveGame();
}

public abstract class Persistence : IPersistence
{

    public abstract void SaveGame();
}

public class SaveToDatabasePersistence : Persistence
{

    public override void SaveGame()
    {
        //Implement SaveToDB
    }
}

public class SaveToXmlPersistence : Persistence
{

    public override void SaveGame()
    {
        //Implement SaveToXML File
    }
}

public static class PersistenceFactory
{
    public static IPersistence GetSaveMethod(string saveMethod)
    {
        switch (saveMethod)
        {
            case "Xml":
                return new SaveToXmlPersistence();
                break;
            case "DB":
                return new SaveToDatabasePersistence();
                break;
            default:
                throw new Exception(string.Format("Unknown Save Method. {0}", saveMethod));
        }
    }
}

The GetSaveMethod would accept a string that would define the concrete type that you wish to return.

The Persistence abstract class is optional. You should use it if you require common functionality between concrete implementations. If you choose not to use it, each concrete type should implement the interface directly.

You haven't specified what language you are using, but in .NET you can use the ConfigurationManager class to read the persistence method from a configuration file.

Lastly

I'm hesitant to use a Singleton due to all the bad reviews I read about it, and I don't really want to have to pass this object around to every class just in case I need to save something.

doesn't quite make sense. A Singleton class is called when necessary. An object being passed to every class just in case you need to use it, is certainly an incorrect implementation of that pattern.

public void SaveGame()
{
    var persitanceMethod = MySingleton.GetInstance().PersitanceMethod;

    var persistence = PersistenceFactory.GetSaveMethod(persitanceMethod);
    persistence.SaveGame();
}

The above code would be an example (from my head) of how you would call a singleton class to retrieve a property from it.

Update

public class Program
{
    private readonly IPersistence _persistence;
    public Program(IPersistence persistence)
    {
        _persistence = persistence;
    }

    public void SaveGame()
    {
         var persistenceObject = PersistenceFactory.GetSaveMethod(_persistence.GameSaveFormat);
         persistenceObject.SaveGame();
    }


问:
File with Apache 2.0 and my modifications
I read the original text of Apache License, Version 2.0 and the explanation in plain English.

OK, I copy a class distributed by The Best Company in the World, their license, and modify the code a bit.

The original file with my changes.

```<code>/*
 * Copyright (C) 2011 The Best Company in the World
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mypackage;

public class MyClass {

    private void someMethod() {
        // Their code
        // My little change
    }
}
</code>```

Then I use MyClass in my application.

Do I need to replace The Best Company in the World with the name
of my company or with my own name? If not, will my project contain two licenses: theirs and mine? Where to save them in this case?

And as far as I understand, I must distribute my application using
Apache Licence, Version 2.0.

Wikipedia says:

The Apache License is widely, but not universally, considered
  permissive in that it does not require a derivative work of the
  software, or modifications to the original, to be distributed using
  the same license (unlike copyleft licenses – see comparison).

答:
Section 4 of the Apache License 2.0 is quite clear on what you must do when you distribute the changed file:

You must not remove the existing copyright claim (the one by 'the Best Company in the World')

You must make it clear the the file has been changed. The easiest way is to simply add your copyright after the original ones:

```<code>Modifications copyright (C) 2013 <your company/name>
</code>```

If you did the modifications on behalf of your company, then that is in most cases also the name that you must put on the copyright notice

You may choose to use a different copyright license for your modifications. However, it is very uncommon for a single file to have multiple portions for which different copyright licenses apply and I doubt that the legal aspects of that have been tested in court, so I would advise against it.

If you don't distribute the modifications (or not outside your company), you don't have to do anything. Copyright licenses only come into play when distributing a program/library.

Body:
Section 4 of the Apache License 2.0 is quite clear on what you must do when you distribute the changed file:

You must not remove the existing copyright claim (the one by 'the Best Company in the World')

You must make it clear the the file has been changed. The easiest way is to simply add your copyright after the original ones:

Modifications copyright (C) 2013 <your company/name>

If you did the modifications on behalf of your company, then that is in most cases also the name that you must put on the copyright notice

You may choose to use a different copyright license for your modifications. However, it is very uncommon for a single file to have multiple portions for which different copyright licenses apply and I doubt that the legal aspects of that have been tested in court, so I would advise against it.

If you don't distribute the modifications (or not outside your company), you don't have to do anything. Copyright licenses only come into play when distributing a program/library.


问:
How should I go about bringing this code under test?
I'm working on an open-source test framework.

90% of my codebase has good test coverage. My main problem area is the command-line entry point. This module began life as a very short script for calling into the domain model (see the call to _run_impl()) and exit with code 1 if the test run failed.

It didn't feel necessary to test that script at the time that I wrote it, but as the project has sprouted features, a number of small changes to the logic in this file have led it to become quite long:

```<code>import argparse
import os
import sys
from . import _run_impl  # a function, in __init__.py, which calls into the domain model
from . import reporting  # a sub-package concerned with writing output to the console

import colorama; colorama.init()

def cmd():
    parser = argparse.ArgumentParser()
    parser.add_argument('-s', '--no-capture',
        action='store_false',
        dest='capture',
        default=True,
        help="Disable capturing of stdout during tests.")
    parser.add_argument('-v', '--verbose',
        action='store_true',
        dest='verbose',
        default=False,
        help="Enable verbose progress reporting.")
    parser.add_argument('--teamcity',
        action='store_true',
        dest='teamcity',
        default=False,
        help="Enable teamcity test reporting.")
    parser.add_argument('--no-random',
        action='store_false',
        dest='shuffle',
        default=True,
        help="Disable test order randomisation.")
    parser.add_argument('path',
        action='store',
        nargs='?',
        default=os.getcwd(),
        help="Path to the test file or directory to run. (default current directory)")
    args = parser.parse_args()

    if args.teamcity or "TEAMCITY_VERSION" in os.environ:
        reporters = (reporting.teamcity.TeamCityReporter(sys.stdout),)
    elif args.verbose:
        reporters = (reporting.cli.ColouredReporter(sys.stdout),)
    elif args.capture:
        reporters = (
            reporting.cli.DotsReporter(sys.stdout),
            type("ColouredCapturingReporter", (reporting.cli.ColouredReporter, reporting.cli.StdOutCapturingReporter), {})(sys.stdout),
            reporting.cli.TimedReporter(sys.stdout)
        )
    else:
        reporters = (
            reporting.cli.DotsReporter(sys.stdout),
            type("ColouredCapturingReporter", (reporting.cli.ColouredReporter, reporting.cli.SummarisingReporter), {})(sys.stdout),
            reporting.cli.TimedReporter(sys.stdout)
        )

    reporter = reporting.shared.ReporterManager(*reporters)

    _run_impl(os.path.realpath(args.path), reporter, args.shuffle)

    if reporter.failed:
        sys.exit(1)
    sys.exit(0)

if __name__ == "__main__":
    cmd()
</code>```

I know that this code has bugs (for example, it should be possible to capture stdout from tests when running in verbose mode), and I've lost confidence in my ability to change this module without breaking something. So I want to write some tests for it - but I only really have experience with test-first development, so I don't really know where to start.

Should the tests be at the unit or integration level? Should I mock the ArgumentParser? Should I mock the reporting module? Should I mock _run_impl? Should I try to bring the whole module under test at the start, or just add tests as I add features? Do I need to refactor to make this method more testable?

Addendum: I think a part of my confusion is due to the fact that this is a relatively thin layer on top of the business logic - it's just there to make it possible to kick-off the test runner from the command line. So I'm feeling confused about what constitutes the service boundary here - in particular, what I should and shouldn't mock.

答:
It seems like the main work is all outside this code. so tests for this code merely need to demonstrate that the calls it will perform are going to be performed reliably .  Possibly you could also test that all of the 'reporters' lists will instantiate valid Reporter objects.  This is all a perfectly legit case for plain old unit testing.

You can certainly break the code up into smaller bits suitable for unit testing -- for example,  the argument parsing could become a function which would be fairly easy to test for different combinations of flags. It seems like the main job of this code is just to fill out the reporters list, so you should make sure that arguments produce the expected lists deterministically.   Increasing testability  might also suggest a refactor in which "reporters" becomes a class rather than a list so you can understand it's contents in a structured way -- that will be more testable and also perhaps more maintainable down the road, though it's hard to tell without knowing the APIs

Overall though this seems like a fairly testable scenario, and (like a lot of UI code ) one which would benefit from a battery of tests that make sure things like poorly formed or inconsistent arguments are handled in a reliable way.

OwnerDisplayName: Benjamin Hodgson

OwnerDisplayName: theodox


问:
Is it possible to check a client side application identity from server side?
Assume there is a web service which is visible publicly but it must be just responsive to a specific client application. Is there any mechanism to check client side application identity to prevent disallowed application to access the service?

For instance, I have a web service which is called by my iOS application. I want to prevent others from calling my web service.

Regarding the fact that others can decompile my client application and create another one which is working the same as mine, I think the only way to avoid unwanted access to the service is to check application identity on server to ensure the request comes from my own application.

Is there any robust and secure way to do that?

答:
No. As you said, anyone can decompile and mimic your own client application. You can never trust input from a client if you do not trust the user of the client.

You can add additional safeguards to attempt to make it more difficult to create a new client. For example, if your client always uses services with a certain max frequency, then a client that connects and issues requests much faster than that may be a hacked client.


答:
Security doesn't come from the client, but in how you implement your web service. Ensuring that you only accept transactions from your own client does little to improve security.

Safe web service operation requires that the service operate independently from the client, and that there are no service APIs that can cause harm to the service or other users of that service.

Authentication, session tracking and SSL are techniques that can improve security of a web service. I would focus on those efforts first before worrying about verifying the origins of a connected client. If your web service is secure then there should be no benefit to anyone who gains access to the source code of the client.

Think of your web service as a black box. The client can connect, issue requests and transactions but at no time does the client ever know what is going on inside the black box.

Title: Is it possible to check a client side application identity from server side?

Body:
Assume there is a web service which is visible publicly but it must be just responsive to a specific client application. Is there any mechanism to check client side application identity to prevent disallowed application to access the service?

For instance, I have a web service which is called by my iOS application. I want to prevent others from calling my web service.

Regarding the fact that others can decompile my client application and create another one which is working the same as mine, I think the only way to avoid unwanted access to the service is to check application identity on server to ensure the request comes from my own application.

Is there any robust and secure way to do that?


问:
ExtJs License for free application
I read much about GPL license. But it couldn't clear my doubt.

I want to develop a small web application using ExtJs because of its features. I won't use much of it. But some features are very good.

Now, as my understanding I think I can give this app to my friend for free for his business needs, right?
Or should I take commercial license for ExtJs?

答:
The Sencha Open Source FAQ covers this use case.

There are 2 important points:

First, both the front end and backend source are likely derived works for the GPL as in this example from the FAQ:

Example

For example: let’s take a mortgage processing software program. Let’s say that the application has a front-end (that generates web pages linked to Ext JS JavaScript) that communicates over JSON/HTTP with a backend service. This backend service contains approval and validation logic for this application alone. Even if only the front-end uses Ext JS code, you should consider that the combination of front and back ends constitutes the application, and the source code for both back and front end would need to be provided to the application’s end users under GPLv3

Second, since ExtJS is run on the client they consider using the web app Conveyance:

Conveyance vs. Propagation

Since Ext JS, Sencha GXT and Sencha Touch are software programs that can run within the browser while disconnected from the network or the rest of a server program; when a Sencha based interface is embedded in a web-page served to a user who does not have an employee relationship with the original licensed entity, we consider that “conveyance” rather than simple web page “propagation” as defined by the GPL v3 has occurred, and the source code of the whole application must be provided to the user.

So you will need to make the source available to the users of the application.  (Much like the AGPL.)

It is clear to me from reading their FAQ that if you intend to use ExtJS in a commercial app they want you to buy a commercial license.

Title: ExtJs License for free application


答:
The last time I implemented security, I used Apache Shiro.  It provided a reliably secure method of implementing a secured client/server access to user data.  Not only did it supply the hashing and crypto algorithms to ensure clear text passwords were not available, it also gave you a framework in which to use your security system.  Each component could verify the current user's authentication level, and then allow/disallow various components to be delivered to the user.

I integrated with a GWT application which allowed for local user accounts, facebook accounts, twitter, linkedin, plaxo, and google+.  It handled all cases without problems.

When Shiro integrates with your web application, it uses your server-side session to store an identifier for the current user.  This is only assigned into the server-side variable when a client successfully provides valid authentication.  They also implement a configurable timeout to restrict how long that authentication is good for.

One thing they can't protect is a man in the middle attack, but it isn't your position to secure against that kind of attack.  Force the use of SSL, and you've covered your ass.

Check out this list of top 10 security risks as a primer.

As far as how that applies to your own client application, you will inherently be insecure. Typically, you would put a unique code within your application to allow only that application to communicate with your web service. Once one person downloads the client, that code is easily available.  Any packet sniffer will be able to see the communications.  Use SSL, and it's more difficult, but a decompile will provide the text.

If you restrict access to users that authenticate via your web service, then you're a good step closer.


问:
How exactly does a program (executable image) and library (pre-compiled image) "link" together?
I know very well of the difference of static versus dynamic linking. What I want to know is, when linking statically (with a library like Winmm.lib on Windows), how does the linker "link" the pre-compiled format with the just compiled binary of the executable?

It does not have to pertain to any specific platform, OS, etc. I just want to know the process of which the linking takes place, and how that static "linking" binds an executable binary together that, when executed, forms a branch with the necessary system calls, routines, and low-level API access.

Basically, how does the compiled file get "put together" statically with the pre-compiled data, especially if they're coded differently?

I mean I  know the library "exposes" routines, but where is the certainty that the called routines always work, and how can this be assured in a linking process?

EXAMPLE: I compile "Hello world.exe", and it is statically linked, and launched from the OS loader. Does something within the binary that the program itself linked with have all the necessary "instructions", "magic number", "checksum", etc. to perform the correct procedures, or the does the OS loader, on the fly, find what's needed to access, i.e. system calls, type of program header, other magic numbers, etc.?

I just want to thoroughly understand my linker's job, and how that linking makes the bonafide binary that the OS can handle, and get to my screen, as opposed to just plain instructions that the OS can't "branch" to any other process with.

答:
A library is basically a collection of object files.  An object file is basically a list of function names and signatures, together with the machine code instructions.  When statically linking, when the linker sees a function call, it finds its name and signature in the object files, copies the machine code instructions to the exe, and changes the function call to point to the place it copied it to.

Dynamic loaders perform a similar task for dynamic libraries.  They load the libraries into memory, look at the function calls the application is making, and change them to point to the library's executable instructions in memory.


问:
Type casting variables in PHP, what is the practical reason for doing this?
PHP, as most of us know, has weak typing.  For those who don't, PHP.net says:

PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which the variable is used.

Love it or hate it, PHP re-casts variables on-the-fly.  So, the following code is valid:

```<code>$var = "10";
$value = 10 + $var;
var_dump($value); // int(20)
</code>```

PHP also allows you to explicitly cast a variable, like so:

```<code>$var = "10";
$value = 10 + $var;
$value = (string)$value;
var_dump($value); // string(2) "20"
</code>```

That's all cool...  but, for the life of me, I cannot conceive of a practical reason for doing this.

I don't have a problem with strong typing in languages that support it, like Java.  That's fine, and I completely understand it.  Also, I'm aware of - and fully understand the usefulness of - type hinting in function parameters.

The problem I have with type casting is explained by the above quote.  If PHP can swap types at-will, it can do so even after you force cast a type; and it can do so on-the-fly when you need a certain type in an operation.  That makes the following valid:

```<code>$var = "10";
$value = (int)$var;
$value = $value . ' TaDa!';
var_dump($value); // string(8) "10 TaDa!"
</code>```

So what's the point?

Take this theoretical example of a world where user-defined type casting makes sense in PHP:

You force cast variable $foo as int → (int)$foo.

You attempt to store a string value in the variable $foo.

PHP throws an exception!! ← That would make sense.  Suddenly the reason for user defined type casting exists!

The fact that PHP will switch things around as needed makes the point of user defined type casting vague.  For example, the following two code samples are equivalent:

```<code>// example 1
$foo = 0;
$foo = (string)$foo;
$foo = '# of Reasons for the programmer to type cast $foo as a string: ' . $foo;

// example 2
$foo = 0;
$foo = (int)$foo;
$foo = '# of Reasons for the programmer to type cast $foo as a string: ' . $foo;
</code>```

A year after originally asking this question, guess who found himself using typecasting in a practical environment?  Yours Truly.

The requirement was to display money values on a website for a restaurant menu.  The design of the site required that trailing zeros be trimmed, so that the display looked something like the following:

Menu Item 1 .............. $ 4
Menu Item 2 .............. $ 7.5
Menu Item 3 .............. $ 3
```

<p>The best way I found to do that wast to cast the variable as a float:</p>

```$price = '7.50'; // a string from the database layer.
echo 'Menu Item 2 .............. $ ' . (float)$price;
```

PHP trims the float's trailing zeros, and then recasts the float as a string for concatenation.

答:
One use for type casting in PHP that I've found:

I'm developing an android app which makes http requests to PHP scripts on a server to retrieve data from a database. The script stores data in the form of a PHP object (or associative array) and is return as a JSON object to the app. Without type casting I would receive something like this:

```<code>{ "user" : { "id" : "1", "name" : "Bob" } }
</code>```

But, using PHP type casting (int) on the user's id when storing it the PHP object, I get this returned to the app instead:

```<code>{ "user" : { "id" : 1, "name" : "Bob" } }
</code>```

Then when the JSON object is parsed in the app, it saves me from having to parse the id to an Integer!

See, very useful.

Body:
One use for type casting in PHP that I've found:

I'm developing an android app which makes http requests to PHP scripts on a server to retrieve data from a database. The script stores data in the form of a PHP object (or associative array) and is return as a JSON object to the app. Without type casting I would receive something like this:

{ "user" : { "id" : "1", "name" : "Bob" } }

But, using PHP type casting (int) on the user's id when storing it the PHP object, I get this returned to the app instead:

{ "user" : { "id" : 1, "name" : "Bob" } }

Then when the JSON object is parsed in the app, it saves me from having to parse the id to an Integer!

See, very useful.


答:
Well, first off, the called routines are not always guaranteed to work. I have quite the experience with making calls to libraries where something or other wasn't quite right and it all falls apart and burns in a glorious fire of seg faults. Ain't nothing there that's "assured" to work.

But if you use the library correctly, and the library is compatible with your environment, then it all works. That specific library's instructions match the expected usage of the surrounding environment. It knows that setting the bit at 0x0045BF will set a pixel on the screen, or whatever.

The linker's roll in all that is not to correctly tell the library how to use the surrounding environment, but to tell the original code how to use the library. A sound driver for 32-bit windows knows how to set the volume up and down. It just doesn't work in 64-bit Linux. You build a program statically linking that driver. The program wants to set the volume up, so it calls its (statically linked) sound driver* to do so. At compile time, the linker connects the volumeUp() function call to the appropriate address in the library which is the actual volumeUp() function. And the library simply knows how to handle sound in 32-bit windows.

*driver, library, same thing. Typically drivers are dynamically linked, but whatever.

Title: How exactly does a program (executable image) and library (pre-compiled image) "link" together?

Body:
I know very well of the difference of static versus dynamic linking. What I want to know is, when linking statically (with a library like Winmm.lib on Windows), how does the linker "link" the pre-compiled format with the just compiled binary of the executable?

It does not have to pertain to any specific platform, OS, etc. I just want to know the process of which the linking takes place, and how that static "linking" binds an executable binary together that, when executed, forms a branch with the necessary system calls, routines, and low-level API access.

Basically, how does the compiled file get "put together" statically with the pre-compiled data, especially if they're coded differently?

I mean I  know the library "exposes" routines, but where is the certainty that the called routines always work, and how can this be assured in a linking process?

EXAMPLE: I compile "Hello world.exe", and it is statically linked, and launched from the OS loader. Does something within the binary that the program itself linked with have all the necessary "instructions", "magic number", "checksum", etc. to perform the correct procedures, or the does the OS loader, on the fly, find what's needed to access, i.e. system calls, type of program header, other magic numbers, etc.?

I just want to thoroughly understand my linker's job, and how that linking makes the bonafide binary that the OS can handle, and get to my screen, as opposed to just plain instructions that the OS can't "branch" to any other process with.


问:
Is securing the credit card data is considered a requirement from the customer
I'm taking an Introduction to Agile Software Development course, The instructor was discussing an example about online store and asked us to write the User Stories and the Conditions of satisfactions and one story was As a user I can commit for marketing card that was selected previously in order to buy my goods, the conditions of satisfactions in this case contained some conditions in addition to The system must secure the Credit Card data across the internet connection using https

I disagreed with that and said this is a thing that must be done, not just in case the user asked me to protect it, and it is a fatal threat like or more important than SQl Injections and this is a non-functional requirement at the technical level and if the user mention it or didn't this must be taken in our development, some project managers in the course showed their disagreement and said this is a time wast on features that the user didn't ask for!, the instructor didn't give my comment any attention and didn't reply to me.

I really think I'm true and not convinced, but all of those trained people disagreed with me[I'm new in the software engineering field but used always to work as a developer], so I'm asking you about this.

答:
Yes, this is clearly a requirement for any modern website to do business. Is it from the customer? Maybe, maybe not. Customers surely want you to prevent their credit card data from being stolen, but there are certainly user stories used to represent technical debt and other infrastructure necessities like this.

Also I hate to see how the credit card data is secured as part of the user story (that's an implementation detail best left to the technical experts), but that's relatively minor in this case.


答:
You bring up an interesting point, as I don't see that many requirements documents would contain things like:

The application shall be free of SQL Injection vulnerabilities, or

The application shall be free of CSRF vulnerabilities,

as such a list might actually be (more or less) unbounded, and securing credit card numbers with HTTPS is an implementation detail.

That said, the requirement probably does exist somewhere, even if it's in the form:

The application shall secure credit cards in a manner acceptable to the credit card companies.

It's a real, testable  requirement, and needs to be documented somewhere.  It's not an implied requirement, any more than "The application shall use best practices while coding" is an implied requirement, even though it is a good idea.

Title: Is securing the credit card data is considered a requirement from the customer

Body:
I'm taking an Introduction to Agile Software Development course, The instructor was discussing an example about online store and asked us to write the User Stories and the Conditions of satisfactions and one story was As a user I can commit for marketing card that was selected previously in order to buy my goods, the conditions of satisfactions in this case contained some conditions in addition to The system must secure the Credit Card data across the internet connection using https

I disagreed with that and said this is a thing that must be done, not just in case the user asked me to protect it, and it is a fatal threat like or more important than SQl Injections and this is a non-functional requirement at the technical level and if the user mention it or didn't this must be taken in our development, some project managers in the course showed their disagreement and said this is a time wast on features that the user didn't ask for!, the instructor didn't give my comment any attention and didn't reply to me.

I really think I'm true and not convinced, but all of those trained people disagreed with me[I'm new in the software engineering field but used always to work as a developer], so I'm asking you about this.


问:
Avoid too complex method - Cyclomatic Complexity
Not sure how to go about this method to reduce Cyclomatic Complexity. Sonar reports 13 whereas 10 is expected. I am sure nothing harm in leaving this method as it is, however, just challenging me how to go about obeying Sonar's rule. Any thoughts would be greatly appreciated.

```<code> public static long parseTimeValue(String sValue) {

    if (sValue == null) {
        return 0;
    }

    try {
        long millis;
        if (sValue.endsWith("S")) {
            millis = new ExtractSecond(sValue).invoke();
        } else if (sValue.endsWith("ms")) {
            millis = new ExtractMillisecond(sValue).invoke();
        } else if (sValue.endsWith("s")) {
            millis = new ExtractInSecond(sValue).invoke();
        } else if (sValue.endsWith("m")) {
            millis = new ExtractInMinute(sValue).invoke();
        } else if (sValue.endsWith("H") || sValue.endsWith("h")) {
            millis = new ExtractHour(sValue).invoke();
        } else if (sValue.endsWith("d")) {
            millis = new ExtractDay(sValue).invoke();
        } else if (sValue.endsWith("w")) {
            millis = new ExtractWeek(sValue).invoke();
        } else {
            millis = Long.parseLong(sValue);
        }

        return millis;

    } catch (NumberFormatException e) {
        LOGGER.warn("Number format exception", e);
    }

    return 0;
}
</code>```

All ExtractXXX methods are defined as static inner classes. For example, like one below -

```<code>    private static class ExtractHour {
      private String sValue;

      public ExtractHour(String sValue) {
         this.sValue = sValue;
      }

      public long invoke() {
         long millis;
         millis = (long) (Double.parseDouble(sValue.substring(0, sValue.length() - 1)) * 60 * 60 * 1000);
         return millis;
     }
 }
</code>```

UPDATE 1

I am going to settle down with a mix of suggestions here to satisfy Sonar guy. Definitely room for improvements and simplification.

Guava Function is just a unwanted ceremony here. Wanted to update the question about current status. Nothing is final here. Pour your thoughts please..

```<code>public class DurationParse {

private static final Logger LOGGER = LoggerFactory.getLogger(DurationParse.class);
private static final Map<String, Function<String, Long>> MULTIPLIERS;
private static final Pattern STRING_REGEX = Pattern.compile("^(\\d+)\\s*(\\w+)");

static {

    MULTIPLIERS = new HashMap<>(7);

    MULTIPLIERS.put("S", new Function<String, Long>() {
        @Nullable
        @Override
        public Long apply(@Nullable String input) {
            return new ExtractSecond(input).invoke();
        }
    });

    MULTIPLIERS.put("s", new Function<String, Long>() {
        @Nullable
        @Override
        public Long apply(@Nullable String input) {
            return new ExtractInSecond(input).invoke();
        }
    });

    MULTIPLIERS.put("ms", new Function<String, Long>() {
        @Nullable
        @Override
        public Long apply(@Nullable String input) {
            return new ExtractMillisecond(input).invoke();
        }
    });

    MULTIPLIERS.put("m", new Function<String, Long>() {
        @Nullable
        @Override
        public Long apply(@Nullable String input) {
            return new ExtractInMinute(input).invoke();
        }
    });

    MULTIPLIERS.put("H", new Function<String, Long>() {
        @Nullable
        @Override
        public Long apply(@Nullable String input) {
            return new ExtractHour(input).invoke();
        }
    });

    MULTIPLIERS.put("d", new Function<String, Long>() {
        @Nullable
        @Override
        public Long apply(@Nullable String input) {
            return new ExtractDay(input).invoke();
        }
    });

    MULTIPLIERS.put("w", new Function<String, Long>() {
        @Nullable
        @Override
        public Long apply(@Nullable String input) {
            return new ExtractWeek(input).invoke();
        }
    });

}

public static long parseTimeValue(String sValue) {

    if (isNullOrEmpty(sValue)) {
        return 0;
    }

    Matcher matcher = STRING_REGEX.matcher(sValue.trim());

    if (!matcher.matches()) {
        LOGGER.warn(String.format("%s is invalid duration, assuming 0ms", sValue));
        return 0;
    }

    if (MULTIPLIERS.get(matcher.group(2)) == null) {
        LOGGER.warn(String.format("%s is invalid configuration, assuming 0ms", sValue));
        return 0;
    }

    return MULTIPLIERS.get(matcher.group(2)).apply(matcher.group(1));
}

private static class ExtractSecond {
    private String sValue;

    public ExtractSecond(String sValue) {
        this.sValue = sValue;
    }

    public long invoke() {
        long millis;
        millis = Long.parseLong(sValue);
        return millis;
    }
}

private static class ExtractMillisecond {
    private String sValue;

    public ExtractMillisecond(String sValue) {
        this.sValue = sValue;
    }

    public long invoke() {
        long millis;
        millis = (long) (Double.parseDouble(sValue));
        return millis;
    }
}

private static class ExtractInSecond {
    private String sValue;

    public ExtractInSecond(String sValue) {
        this.sValue = sValue;
    }

    public long invoke() {
        long millis;
        millis = (long) (Double.parseDouble(sValue) * 1000);
        return millis;
    }
}

private static class ExtractInMinute {
    private String sValue;

    public ExtractInMinute(String sValue) {
        this.sValue = sValue;
    }

    public long invoke() {
        long millis;
        millis = (long) (Double.parseDouble(sValue) * 60 * 1000);
        return millis;
    }
}

private static class ExtractHour {
    private String sValue;

    public ExtractHour(String sValue) {
        this.sValue = sValue;
    }

    public long invoke() {
        long millis;
        millis = (long) (Double.parseDouble(sValue) * 60 * 60 * 1000);
        return millis;
    }
}

private static class ExtractDay {
    private String sValue;

    public ExtractDay(String sValue) {
        this.sValue = sValue;
    }

    public long invoke() {
        long millis;
        millis = (long) (Double.parseDouble(sValue) * 24 * 60 * 60 * 1000);
        return millis;
    }
}

private static class ExtractWeek {
    private String sValue;

    public ExtractWeek(String sValue) {
        this.sValue = sValue;
    }

    public long invoke() {
        long millis;
        millis = (long) (Double.parseDouble(sValue) * 7 * 24 * 60 * 60 * 1000);
        return millis;
    }
}
</code>```

}

UPDATE 2

Though I added my update, it is only that much worth the time. I am going to move on since Sonar now does not complains. Don't worry much and I am accepting the mattnz answer as it is the way to go and don't want to set a bad example for those who bumps on to this question. Bottom line -- Don't over engineer for the sake of Sonar (or Half Baked Project Manager) complains about CC. Just do what's worth a penny for the project. Thanks to all.

答:
You might consider using an enum for storing all your available cases and predicates for matching values. As mentioned before your function is readable enough just to leave it unchanged. Those metrics are there to help you not the other way around.</p>

```<code>//utility class for matching values
private static class ValueMatchingPredicate implements Predicate<String>{
    private final String[] suffixes;

    public ValueMatchingPredicate(String[] suffixes) {
        this.suffixes = suffixes;
    }

    public boolean apply(String sValue) {
        if(sValue == null) return false;

        for (String suffix : suffixes) {
            if(sValue.endsWith(suffix)) return true;
        }

        return false;
    }

    public static Predicate<String> withSuffix(String... suffixes){
        return new ValueMatchingPredicate(suffixes);
    }
}

//enum containing all possible options
private static enum TimeValueExtractor {
    SECOND(
        ValueMatchingPredicate.withSuffix("S"),
        new Function<String, Long>(){
            public Long apply(String sValue) {  return new ExtractSecond(sValue).invoke(); }
        }),

    MILISECOND(
        ValueMatchingPredicate.withSuffix("ms"),
        new Function<String, Long>(){
            public Long apply(String sValue) { return new ExtractMillisecond(sValue).invoke(); }
        }),

    IN_SECOND(
        ValueMatchingPredicate.withSuffix("s"),
        new Function<String, Long>(){
            public Long apply(String sValue) { return new ExtractInSecond(sValue).invoke(); }
        }),

    IN_MINUTE(
        ValueMatchingPredicate.withSuffix("m"),
        new Function<String, Long>(){
            public Long apply(String sValue) {  return new ExtractInMinute(sValue).invoke(); }
        }),

    HOUR(
        ValueMatchingPredicate.withSuffix("H", "h"),
        new Function<String, Long>(){
            public Long apply(String sValue) {  return new ExtractHour(sValue).invoke(); }
        }),

    DAY(
        ValueMatchingPredicate.withSuffix("d"),
        new Function<String, Long>(){
            public Long apply(String sValue) {  return new ExtractDay(sValue).invoke(); }
        }),

    WEEK(
        ValueMatchingPredicate.withSuffix("w"),
        new Function<String, Long>(){
            public Long apply(String sValue) {  return new ExtractWeek(sValue).invoke(); }
        });

    private final Predicate<String>      valueMatchingRule;
    private final Function<String, Long> extractorFunction;

    public static Long DEFAULT_VALUE = 0L;

    private TimeValueExtractor(Predicate<String> valueMatchingRule, Function<String, Long> extractorFunction) {
        this.valueMatchingRule = valueMatchingRule;
        this.extractorFunction = extractorFunction;
    }

    public boolean matchesValueSuffix(String sValue){
        return this.valueMatchingRule.apply(sValue);
    }

    public Long extractTimeValue(String sValue){
        return this.extractorFunction.apply(sValue);
    }

    public static Long extract(String sValue) throws NumberFormatException{
        TimeValueExtractor[] extractors = TimeValueExtractor.values();

        for (TimeValueExtractor timeValueExtractor : extractors) {
            if(timeValueExtractor.matchesValueSuffix(sValue)){
                return timeValueExtractor.extractTimeValue(sValue);
            }
        }

        return DEFAULT_VALUE;
    }
}

//your function
public static long parseTimeValue(String sValue){
    try{
        return TimeValueExtractor.extract(sValue);
    } catch (NumberFormatException e) {
        //LOGGER.warn("Number format exception", e);
        return TimeValueExtractor.DEFAULT_VALUE;
    }
}
</code>```

Body:
You might consider using an enum for storing all your available cases and predicates for matching values. As mentioned before your function is readable enough just to leave it unchanged. Those metrics are there to help you not the other way around.

//utility class for matching values
private static class ValueMatchingPredicate implements Predicate<String>{
    private final String[] suffixes;

    public ValueMatchingPredicate(String[] suffixes) {
        this.suffixes = suffixes;
    }

    public boolean apply(String sValue) {
        if(sValue == null) return false;

        for (String suffix : suffixes) {
            if(sValue.endsWith(suffix)) return true;
        }

        return false;
    }

    public static Predicate<String> withSuffix(String... suffixes){
        return new ValueMatchingPredicate(suffixes);
    }
}

//enum containing all possible options
private static enum TimeValueExtractor {
    SECOND(
        ValueMatchingPredicate.withSuffix("S"),
        new Function<String, Long>(){
            public Long apply(String sValue) {  return new ExtractSecond(sValue).invoke(); }
        }),

    MILISECOND(
        ValueMatchingPredicate.withSuffix("ms"),
        new Function<String, Long>(){
            public Long apply(String sValue) { return new ExtractMillisecond(sValue).invoke(); }
        }),

    IN_SECOND(
        ValueMatchingPredicate.withSuffix("s"),
        new Function<String, Long>(){
            public Long apply(String sValue) { return new ExtractInSecond(sValue).invoke(); }
        }),

    IN_MINUTE(
        ValueMatchingPredicate.withSuffix("m"),
        new Function<String, Long>(){
            public Long apply(String sValue) {  return new ExtractInMinute(sValue).invoke(); }
        }),

    HOUR(
        ValueMatchingPredicate.withSuffix("H", "h"),
        new Function<String, Long>(){
            public Long apply(String sValue) {  return new ExtractHour(sValue).invoke(); }
        }),

    DAY(
        ValueMatchingPredicate.withSuffix("d"),
        new Function<String, Long>(){
            public Long apply(String sValue) {  return new ExtractDay(sValue).invoke(); }
        }),

    WEEK(
        ValueMatchingPredicate.withSuffix("w"),
        new Function<String, Long>(){
            public Long apply(String sValue) {  return new ExtractWeek(sValue).invoke(); }
        });

    private final Predicate<String>      valueMatchingRule;
    private final Function<String, Long> extractorFunction;

    public static Long DEFAULT_VALUE = 0L;

    private TimeValueExtractor(Predicate<String> valueMatchingRule, Function<String, Long> extractorFunction) {
        this.valueMatchingRule = valueMatchingRule;
        this.extractorFunction = extractorFunction;
    }

    public boolean matchesValueSuffix(String sValue){
        return this.valueMatchingRule.apply(sValue);
    }

    public Long extractTimeValue(String sValue){
        return this.extractorFunction.apply(sValue);
    }

    public static Long extract(String sValue) throws NumberFormatException{
        TimeValueExtractor[] extractors = TimeValueExtractor.values();

        for (TimeValueExtractor timeValueExtractor : extractors) {
            if(timeValueExtractor.matchesValueSuffix(sValue)){
                return timeValueExtractor.extractTimeValue(sValue);
            }
        }

        return DEFAULT_VALUE;
    }
}

//your function
public static long parseTimeValue(String sValue){
    try{
        return TimeValueExtractor.extract(sValue);
    } catch (NumberFormatException e) {
        //LOGGER.warn("Number format exception", e);
        return TimeValueExtractor.DEFAULT_VALUE;
    }
}


问:
We have a custom program that generates all the stored procs and classes for the Data Tier. Where will I put the generated classes?
This is more of an architectural question regarding MVC and Data Access:

We have a custom program that generates all the stored procs and classes for the Data Tier from the MS SQL database. It's pretty nice as it generates a base class with the basic CRUD operations which includes ForeignKey reads. It also generates the plural version of the class to return the collections of objects.

For the next phase of our application we are planning on using MVC but we were hoping to continue using this great tool. Where will I put the generated classes in my new MVC application? I have seen people create an Infrastructure folder for their data access logic.

Is it a good idea to continue using this tool or should we be converting to the Entity Framework?

Also if the DAL is returning my objects and lists of objects what will I put in my Model layer?

答:
It lives in the Model part of MVC.

where you physically put those generated classes? It doesn't really matter as far as MVC is concerned.  However it makes sense to group things into logical places.  But MVC wise, you could have an entire MVC application in 1 file.


答:
Putting on my IT Director hat I see a few no-gos here:

Risk of data corruption. Perhaps more percieved than real but end of the day this is a non-transactional file type DB that does not have much if any recourse to bad writes besides asking if you've got a recent backup. Speaking of which . . .

How do I back this thing up? In a manner I know I've got a good copy. Preferably without taking the app offline.

How can I secure access to the DB? My general understanding is SQL lite has none outside of the filesystem access, which is a decent start but not the be-all, end-all. Especially for web apps where you might want more graduated permissions than DBA or nothing.

From a developer point of view I think it is important to know why SqlLite is the default -- it is because it is easy and it demos well. If you are "selling" a platform to new developers, being able to fire up a working web app with minimal fuss is key. And having to stand up and properly configure a database server would be a massive stumbling block to be avoided.

Title: Internal-use websites: Is there a compelling case against SQLite?

Body:
Many web frameworks, such as Flask or Django use SQLite as their default database.  SQLite is compelling because it's included in python, and administrative overhead is pretty low.

However, most high traffic public production sites wind up using a heavier database: mySQL, Oracle, or postgresql.

The questions:

Assume:

Site traffic is moderate, and concurrent read/write access to the database will happen

We will use SQLAlchemy with SQLite write locks (although this comment makes me a little nervous)

The database will contain perhaps 60,000 records

Data structures do not require advanced features found in heavier databases

Is there ever a compelling case against SQLite concurrency for websites that  serve as moderate-traffic internal corporate tools?  If so, what conditions will cause SQLite to have concurrency problems?

I'm looking for known specific root causes, instead of general fear / unsubstantiated finger pointing.


问:
Verbose or concise logging
I was wondering how much data should be logged.

I know this deeply depends on multiple factors. But it can still be hard to find the golden middle way.

Lets say I have an application where people can create and administrate a user. Furthermore they are able to create/read/update/delete other objects within the application.

If the application has many users it can be an issue if too much data is logged. If all DTO classes and their contents is logged everytime a user or any other object is edited/delete/etc. the logs could get extremely large. But if you only log a little line saying "User 'blabla' was created/edited/etc." you might have trouble debugging or recreating bugs as you dont have the exact state of the objects when the error happened.

Where I currently work we rarely log data, but instead log error messages and stack traces, but I've also previously worked at places where they logged every single bit of information that can be useful in a future debugging scenario.

I was wondering what other people do and think about this? How much data do you log for future debugging information? - is there such a thing as a "correct" amount of data logged?

答:
I was debugging an app that streamed video data... the logging was insufficient to diagnose a particularly troublesome problem (though the problem was easy once we'd found it), so we had to put logging in the video playback code.. yup, 25 (or so) log calls per second.

So your problem is never going to be "how little logging can I get away with", but "how can I manage truly massive amounts of logging so I can get useful information out of it". The managing of even small amounts of log data is the same exact problem, so concentrate your efforts on that - that means, making sure you can enable sections of logging, or print out parts so they can be clearly identified within a mass of other, useless, log information.

I always log lots of data, and audit it too. Once your code leaves your hands and gets installed on a customer site, and all they can give you to help diagnose a problem is the log files, you can't go back and add more logging to pinpoint the bit that went wrong.

Title: Verbose or concise logging


答:
The likeliest reason is: it has to do with history. Java's ancestor, Oak, only had three access levels: private, protected, public.

Except that private in Oak was the equivalent of package private in Java. You can read section 4.10 of Oak's Language  Specification (emphasis mine):

By default all variables and methods in a class (including constructors) are private. Private variables and methods can be accessed only by methods declared in the class, and not by its subclasses or any other classes (except for classes in the same package).

So to your point, the private access, as known in Java, was not there originally. But when you have more than a few classes in a package, not having private as we know it now would lead to a nightmare of name collision (for example, java.until.concurrent has close to 60 classes), which is probably why they introduced it.

However the default package access (originally called private) semantics were not changed between Oak and Java.


问:
Stuff every programmer needs while working
I've been tasked with creating a fun and relaxing environment, one thing I know that I want is ergonomic mice and keyboards, others have suggested exercise balls and bands.

What is it that every programmer needs while working? What might not be necessary but would be nice to have anyway?

Note: this question was asked previously, but has been recommended to be posted here. See this link for the previous responses: https://stackoverflow.com/questions/3911911/stuff-every-programmer-needs-while-working-closed

答: May be someone has already said it, but there should be a fortress of solitude and if that is not feasible atleast a corner of solitude.</p>

ContentLicense: CC BY-SA 2.5