答: This sounds like a good opportunity to use the Strategy design pattern. You will have a data access strategy that will check the environment and execute the proper code depending on what the back end is. "Checking the environment" could be something as simple as using an environment variable or something more high level like injecting the appropriate query handlers during application init (easily done using Spring or another DI framework).

Title: Working with two different database types for one application

Body:
Software: Java J2EE Application hosted on Tomcat Server.

UPDATE

The current software is JAVA Web application containing just JSP and Servlets no frameworks or anything. Simple  JSP and Servlets communicating with Oracle DB

I have no issues in re-writing the application, but since the two
  copies of it will be maintained I want the code to be same and so when
  applying a change I need to apply them same on both places. Instead of
  writing two sets of different code I want to keep the code same while
  and intermediate layer to handle the DB communication

Software with same code is being hosted and run at two different locations miles away(two separate instances).
Initially the back-end database of the application was same(viz. Oracle).
Now one of the location has stopped the support on oracle and is switching to the Open Source Postgres.

So now the (to be) scenario is something like this

Software: Java J2EE Application hosted on Tomcat Server.

Database 1: Oracle

Database 2: Postgres

At any point of time the application will be using only one database as they are running different instances.

Can an intermediate be added that can interpret the request from application and query depending on the database which needs to be used to fetch data. if yes which is the best option for that.

All this so that every time there is a change in the application, the change takes place uniquely on each copies and an overhead of maintaining two different copies can be avoided.


问:
Options for repeated distributed task

Scenario

My project has a need to periodically scan the database and notify administrators for particular issues. For example:

Any errors in the logs since last update?

Do values match expected value from external source?

New clients?

My nodes (plain old windows services) are currently using Azure Service Bus QueueClient for other distributed tasks, so my original thought was to do something with this same component. However, this proved pretty challenging (see below).

From brainstorming I've come up with the following possible options:

Azure ServiceBus QueueClient

Description: Upon receiving a task, the message handler will enqueue a new message set for X in the future.

For example:

```<code>var client = QueueClient.Create("DetectErrors");
var options = /* ... */

client.OnMessage((message) => {
    client.Send(new BrokeredMessage() {
        ScheduledEnqueueTimeUtc = DateTime.Today.AddDays(1)
    });

    if (DetectStuffInDb())
    {
        SendEmail();
    }
}, options)
</code>```

Issue: How to fire that 1st message? This needs to fire when there is no pending message and only fire a single message (not one per node as might be the case if all nodes start the same time).

Azure QueueClient + WebJob

Description: Use an Azure Webjob to hit an endpoint on my WebApi, which will enqueue a new message. (a slight derivation of this would be to use Azure Automation + Runbook to enqueue a message)

Issue: Seems odd to make so many 'hops' to handle each task. [WebJob] -> [WebApi] -> [Queue] -> [Node]. Additionally, this would make development\testing a little difficult since the WebJob may not have access to a localhost WebApi.

Task.Delay + DB

Description: Use Task.Delay to space out recurring tasks on each distributed node & verify with the DB if another node is currently handling the task. Something like

```<code>var id = Cmd("SELECT [Id] FROM [T]");
while (true)
{
    var newId = Guid.NewGuid();
    Cmd("UPDATE [T] SET [Id] = '<newId>' WHERE [Id] = '<id>'");
    id = Cmd("SELECT [Id] FROM [T]");

    if (newId == id)
    {
        if (DetectStuffInDb())
        {
            SendEmail();
        }
    }

    await Task.Delay(x);
}
</code>```

Issues: Requires a lot of querying of the database by all the nodes.

Question

Any suggestions to how to best handle this scenario?

Is there a better way to handle this scenario that doesn't require timed\recurring tasks?

答:
My advice would be to not overcomplicate your program attempting to accomodate task scheduling.  When it comes to these things, I generally prefer to hinge on cron or windows task scheduler to deal with the specifics of when.  This leaves you the possibility to focus only on the how, and you can disregard having to worry about an interface and all that entails in order to set up a scheduled task.

Just create a simple batch file that performs the request to your server and schedule it to run once a day.  I imagine this is the sort of thing that a systems administrator would have to deal with and certainly not your typical user, so you can make your boss happy by getting it up and working in less time and still having all the functionality you potentially require.  While it is true that this makes your program operating system dependent, it would take little work to get the same thing to work using cron, and it would seem in your case, this discussion is not even relevant.

Alternatively, you could search for a library that provides this support.  In any case, I would strongly encourage you to resist the temptation to code this yourself.  This is the type of thing that has been done many times over, and if you attempted to do it yourself, aside from lose time, you might discover some serious issues down the road that, if you're lucky, won't get you fired.  Don't take the risk and don't reinvent the wheel.  It is my personal idea that the best of us programmers aren't those who can write a better version of an algorithm than you, but rather those who gracefully admit that such things have already been written and must only be pieced together with care.

Please let me know how it turns out.  :)

ContentLicense: CC BY-SA 3.0

Title: Options for repeated distributed task


问:
In C++, how to call an 'init' routine as a class is loaded?
I have a program that loads a bunch of "addons" (different meters that measure and display system values).

The "addons" have "grown" over time and the code of what addons to "activate",
and how many of each (if there is more than one of the "device" in the
system (cpu's, net-interfaces, etc)  is hard-coded into the master.  Ug
(and ick).

What I want is for each addon-meter to place it's name and init-routine-addr
into an array as they are loaded.  Right now, what meters that are loaded
are fixed in the master at compile time.  What I want is for the possibility
of dynamic loading, but more importantly, for external "script-extensions"
(that could measure "almost anything" and rely on the master to display
the collected data (like a script that would read outdoor temperature via
some 3rd party device).  In other words -- long after the master has been
compiled, I want to provide the ability for other addon meters to be added
as long as they supply a specific callable API.

Thus, as a new extension is added, I need some init routine to be called
as it loads that will place the new meter-name and routine to be called
in a class-singleton that has an array of the extension names and
their init-routine addresses (as in a dynamically loaded extension).

Then when execution starts, each extension will already have have "registered"
itself with a central list that the "master" can look at and know what
to call.

In Perl, I've used something in a "BEGIN{...} block" in loaded extensions
to call a Plug_Common->register("plugin name", \%Plugin_Description_Data); so when the main routine started it would look in the plugin-registry to see
what was available, dynamically, at runtime.

The question is, how do I do this in C++?

I've setup register routine, but I've no idea how to have the extensions
get their "name & address" registered before the main-master runs.  Theoretically, since some of the extensions could be added via scripts long after the main-master was written -- it wouldn't be able to know their names in advance.

Off the top of my head, I can only think of a "user-edited" static text file, that might be able to have the master, "somehow(?!)" call each extensions init and 'get_config' routine.  Then I can get rid of all the 'extension/meter-specific'-knowledge out of the the master.  I don't like the text-file idea as it's too prone to user-error -- having something being able to automatically call a register-function as it is loaded, seems much less likely to have problems like the static-config file being out-of-sync with what extensions can be used on the system.

Any ideas? (I'd rather not have to build in a copy of something like Perl to handle the dynamic "loadability" of modules...to me, that would be 'ugly'...

Seem a bit unreliable for the master program to try to look through some
symbol table at runtime -- especially with C++'s strong typing.  I keep coming up with flaws in virtually every method I think of. :-(.  Anyone know a better way?  ;-)...

Update:

Had a thought (well more than one, but this one is a bit unconventional, but might work)  What if each of the plugins declared a shared pointer to a global list in the master?)  If the shared pointers were used in module level inits, then wouldn't the shared 'use count' be incremented as the modules were loaded?...hmmm... I don't know yet how to get the modules' addresses into the main array (without them getting any execution time), but if I can figure out a way for an initializer statement using the shared_ptr, then since loading it a non-multithreaded (at least at this point) if that pointer could be leveraged to increment and store the address of an init function, in a global array, that might give me my dynamic config?  Right now, the only thing I know for sure is that shared pointers do have an accessible 'use_count' -- which would only help me in determining how many plugins had registered.  Maybe there is no way to make this work, but just a thought (at 5:45am after I've been up all night... so, may be completely flawed and I just don't see it yet...;-))...   Anyway, thought I'd add my latest thoughts;  For scripts I'm thinking of splitting off that type of plugin into a separate handler that would have to read some config... I don't really like it, but it does isolate those things that wouldn't load @ program start time...  Anyone think it is possible to leverage the shared-pointer to do this?

答:
On Linux, if compiling code with GCC, the static data's constructor is run at dlopen(3) time. See also the visibility attribute and the GCC specific __attribute__((constructor)) for functions.

However, you should define a plugin convention: which names (for extern "C" C++ functions inside plugins) are used, with which signatures, in what order, etc.

For example, you could decide that every plugin should have a function extern "C" void my_plugin_init(void); which your program would run (after having dlsym-ed it) when loading a plugin, etc... That my_plugin_init might register some other functions (perhaps by adding them to some global std::map<std::string,std::function<BaseClass*(int)>> variable, etc....)

The Qt Plugins framework could inspire you.

ContentLicense: CC BY-SA 4.0


问:
Why JavaScript? What's the advantages?
This is not a simple question, but I was thinking, what advantages are really there in the JavaScript language?

We all use JavaScript on the browser, of course, there is no other choice (you can use transpilers, but in the end its still javascript), and I know, it's a relatively easy language to learn, but, imagine we could use any language instead of JavaScript, in which situation would JavaScript still be a better choice? Not only in the browser, but on other places too?

I don't want to consider the community and the libraries around the language, or its learning curve. I want to consider the language itself. What can JavaScript do that other languages can't, or what JavaScript does better than most others?

Don't take me wrong, I love javascript and work with it every day, but I couldn't answer that question.

Thanks!

答:
Javascript ressembles a Scheme like language, with a different syntax, a weird prototype semantics, and ugly rules (like for evaluation of {} + [] etc...). It was probably (for economical and social reasons) under-specified and under-designed. Later, the common implementation (inside browsers) became a de facto standard and inspired the more official specifications.

Once Javascript appeared in the Web landscape, it has been tried and has grown because of an extenality - the business network of all the corporations using it. Once a lot of people is using it, there is not enough incentive to replace it by something better.

Scheme (and Common Lisp) and Python have their advantages (but I prefer Scheme syntax over Javascript's).

For example, DSSSL was heavily inspired by Scheme.

Title: Why JavaScript? What's the advantages?


问:
Why am I getting field visibility warnings in Sonar?
Some static analysis tools flag non-private fields with

Variable '[nameHere]' must be private and have accessor methods.

Sonar consistently presents such warnings and wants to change all protected variables in my code to private, why is this? I'm yet to see a protected variable in my work that hasn't raised this warning.

答:
Fields that are protected are not hidden strongly enough for many static analysis tools such as sonar, pmd, or checkstyle.  protected fields are visible to subclasses (docs) and allow subclasses to change the state of the class without going through accessor methods which may cause problems in the methods of the superclass.

So, that's why its complaining about protected fields.  Unless you are specifically designing for extension (that the class should be subclassed), it is probably better to use the default package-private level for fields and methods that you want visible to tests (or other classes in the package).

Personally, I've never had use for a protected variable field within a class - even those that are subclassed.  protected final fields occasionally, but never a variable field.  On the other hand, I've often used default level on methods for testing and (more often than protected final though still uncommon) /* default */ final fields.

The purpose of the warning is to get you to think more about how you are actually presenting the class and the contract you are presenting to others for its use.  If you have it be too permissive, it is all too easy for co-workers to take short cuts and tinker with the innards of the class (I once saw someone create an inner class that subclassed another class and create public methods to access the protected fields). Reducing the visibility of fields and methods can be a painful refactoring.

Start out with the most restrictive permissions and as you find real need for a design that is more permissive, open it up. This is what the static analysis tools are encouraging you to do.


答:
The question is actually two questions rolled into one:

Why a scripting language?

Of all scripting languages, why javascript?

Why a scripting language?

The major idea behind the use of scripting languages is this:

Applications often need customization, and some times the level of customization offered by options and styles is not enough.  By including a scripting language in your application you allow your users to heavily customize your application, without having to give them the source code of your application and without forcing them to learn and use software development tools like compilers.

Also, scripting languages generally have the advantage of being highly self-contained. Adding a scripting language to any application is relatively easy: you instantiate some scripting engine within your program, you give it a series of interfaces that will be visible by the scripts, and then you give it a script to run. The script is (for all practical purposes) physically incapable of accessing any functionality of your execution environment other than the interfaces that you supplied.

Also, scripting languages are generally more high-level than regular programming languages, meaning that they are somewhat more removed from the actual machine. (Scripting language programmers are generally not concerned with how many bits long their ints are.) This, in combination with their high level of containment, makes scripting languages highly portable: if you keep the interfaces available to your script minimal, then all you need to do in order to make your scripts runnable on a multitude of operating environments out there is to implement those minimal interfaces on each targeted operating  environment.

All this makes scripting languages ideal for running on browsers, which are native to all sorts of diverse systems out there, and where you obviously do not want potentially malicious code downloaded from any place that you visit on the web to have access to your computer. So, javascript running on a browser generally has a very small view of the world; basically, its entire world usually consists of the document model of the current page, plus a few other services for communicating with the interwebz, usually with the server from which the script originated.  Contrast this with a real language, which generally comes together with rich libraries that (fortunately or unfortunately, this is not the right place for this discussion,) allow code to do pretty much anything it pleases on the machine on which it is running.

Of all scripting languages, why javascript?

That having been said, the question of why javascript in particular still remains.  I suppose that the answer to this question is a lot less technical.  It probably only has to do with history and politics.

Javascript was invented by a USAian, who at the time was working for Netscape, which at the time was the one company making the one browser that everyone was using to access that brand new thing known as the internet.  So, it caught on.  When microsoft launched their own browser shortly thereafter, they tried to play the same trick with a scripting language of their own invention: vbscript.  Luckily, it flopped.

Python was available at around the same time as javascript, (if not slightly earlier,) but its creator was Dutch, and he was not affiliated with any major companies at that time, so that's probably the only reason why our browsers are (unfortunately) running javascript instead of Python.

Title: Why JavaScript? What's the advantages?

Body:
This is not a simple question, but I was thinking, what advantages are really there in the JavaScript language?

We all use JavaScript on the browser, of course, there is no other choice (you can use transpilers, but in the end its still javascript), and I know, it's a relatively easy language to learn, but, imagine we could use any language instead of JavaScript, in which situation would JavaScript still be a better choice? Not only in the browser, but on other places too?

I don't want to consider the community and the libraries around the language, or its learning curve. I want to consider the language itself. What can JavaScript do that other languages can't, or what JavaScript does better than most others?

Don't take me wrong, I love javascript and work with it every day, but I couldn't answer that question.

Thanks!


答:
In the early days of Netscape, there was a new technology that was all the rage.  Java. This wasn't the Java that we know and love (for some definition of 'love') today, but rather Java Applets.

Java applets had a serious flaw though - they couldn't interact with the page that enclosed them. This severly limited their utility.  And so, the makers of the leading web browser at the time took it upon themselves to write a simple scripting language that was embedded within the browser that would be able to bridge the gap between the page itself and the applet.  And thus JavaScript was born.

The key role of JavaScript in those days was to be able to invoke methods in the applet container and also be able to be invoked by the applet itself... and some DOM tinkering to make that interaction useful.  It was based on a very simple functionalish language with some syntax that wasn't foreign to the Java coders it was courting.

Read the above again. The thing JavaScript provided was interaction with Java applets in the web page. No other languages did this.

And that is why JavaScript and not Python or Perl or TCL or any of its contemporary scripting languages is in the browser. Those other scripting languages weren't designed with this bridge in mind and grafting that bridge into the language involved too much modification to those languages - and whats more, they were outside of the control of Netscape.

So, for back then...

It was a small language that provided a key piece of browser technology at a critical time

Lots of people learned it as part of the browser stack

So what does it do better now? Being easy to access and accessible for new programmers and provide rapid feedback for doing visible things (doing things on a web page) that hasn't been around since the days of low res graphics in Basic in the early '80s.  Sure you can do neat things with Python or Lua or Ruby... but you can't just toss it in a web page and say "look what I did" the way you can with JavaScript. Everyone who has a computer or smart phone can see it and appreciate what was done.

Title: Why JavaScript? What's the advantages?


问:
How would you design a user database with custom fields
This question is around how should I design a database, it can be relational / nosql databases, depending on what will be the better solution

Given a requirement where you'll need to create a system that will involve a database to track "Company" and "User". A single user always only belong to one company

A user can only belong to one company

A company can have many users

The design for "Company" table is quite straightforward.
Company will have the following attributes / columns: (let's keep it simple)

```<code>ID, COMPANY_NAME, CREATED_ON
</code>```

First scenario

Simple & straight forward, users all have the same attribute, so this can be easily done in relational style, user table:

```<code>ID, COMPANY_ID, FIRST_NAME, LAST_NAME, EMAIL, CREATED_ON
</code>```

Second scenario

What happen if different companies want to store different profile attribute for their user. Each company will have a defined set of attributes that would apply to all users of that company.

For example:

Company A wants to store: LIKE_MOVIE (boolean), LIKE_MUSIC (boolean)

Company B wants to store: FAV_CUISINE (String)

Company C wants to store: OWN_DOG (boolean), DOG_COUNT (int)

Approach 1

the brute force way is to have a single schema for the user and let them have nulls when they dont belong to the company:

```<code>ID, COMPANY_ID, FIRST_NAME, LAST_NAME, EMAIL, LIKE_MOVIE, LIKE_MUSIC, FAV_CUISINE, OWN_DOG, DOG_COUNT, CREATED_ON
</code>```

Which is kinda nasty because you will end up with a lot of NULLS and user rows that have columns that are irrelevant to them (ie. all users belonging to Company A has NULL values for FAV_CUISINE, OWN_DOG, DOG_COUNT)

Approach 2

a second approach, is to have "free form field":

```<code>ID, COMPANY_ID, FIRST_NAME, LAST_NAME, EMAIL, CUSTOM_1, CUSTOM_2, CUSTOM_3, CREATED_ON
</code>```

Which would be nasty on its own since you have no idea what custom fields are, the data type will not be reflective of the values stored (eg. we'll store int value as VARCHAR).

Approach 3

I have looked into PostgreSQL JSON field, in which case you will have:

```<code>ID, COMPANY_ID, FIRST_NAME, LAST_NAME, EMAIL, CUSTOM_PROFILE_JSON, CREATED_ON
</code>```

In this case, how would you be able to apply different schemas to a user?
A user with Company A will have schema that looks like

```<code> {"LIKE_MOVIE":"boolean", "LIKE_MUSIC": "boolean"}
</code>```

While a user with Company C will have a different schema:

```<code> {"OWN_DOG ":"boolean", "DOG_COUNT": "int"}
</code>```

How should I solve this issue? How can I design database properly to allow for this flexible schema for a single "object" (User) based on the relationship they have (Company)?

relational solution? nosql solution?

Edit: I've also thought about a "CUSTOM_PROFILE" table which will essentially store user attributes in rows rather than columns.

There are 2 problems with this approach:

1) The data grows per user grow as rows rather than columns - and this mean to get a full picture of the user, a lot of joins need to be done, multiple joins to the "custom profile" table on the different custom attributes

2) The data value is always stored as VARCHAR to be generic, even if we know the data is supposed to be integer or boolean etc

答:
Use a NoSQL database. There would be company and user documents. The users would have part of their schema dynamically created based on a user template (text to indicate fields/types for that company.

```<code>\Company\<uniqueidentifier>
    - Name: <Name>
    - CreatedOn: <datetime>
    - UserTemplate: <Text>

\User\<uniqueidentifier>
    - COMPANY_ID: <ID>
    - FIRST_NAME: <Text>
    - LAST_NAME: <Text>
    - EMAIL: <Text>
    - CREATED_ON: <datetime>
    - * Dynamically created fields per company
</code>```

This is how it might look in something like Firebase.com You would have to learn how to do it in whatever one you choose.

Body:
Use a NoSQL database. There would be company and user documents. The users would have part of their schema dynamically created based on a user template (text to indicate fields/types for that company.

\Company\<uniqueidentifier>
    - Name: <Name>
    - CreatedOn: <datetime>
    - UserTemplate: <Text>

\User\<uniqueidentifier>
    - COMPANY_ID: <ID>
    - FIRST_NAME: <Text>
    - LAST_NAME: <Text>
    - EMAIL: <Text>
    - CREATED_ON: <datetime>
    - * Dynamically created fields per company

This is how it might look in something like Firebase.com You would have to learn how to do it in whatever one you choose.


问:
how to nicely use constant std::string in c++
In my current code project, there is an awful lot of constant strings I use to print out error messages.

Hardcoding such strings is generally considered to be bad practice.
Now I'm searching for a "clean way" to include these strings in my program. Therefore I've written a "constants.h" and "constants.cpp" which looks something like

```<code>#ifndef CONSTANTS_H_
#define CONSTANTS_H_

extern std::string error_message_1;

#endif
</code>```

and the constants.cpp:

```<code>#include "constants.h"

std::string error_message_1 = "this is just a sample, not my actual naming convention. move on the the question ;-)"
</code>```

So you might see the problem I have with this: due to a lot of error messages, the variable name itself is fairly long. The error message is even longer, so it crashes the standard 80 characters in one line of code.

Obviously I want my code nice and clean. I don't like going far beyond the 80 charactes per line of code. I don't like somthing like the following either:

```<code>std::string error_message_1 = "this is just a sample about how to"
                              " have one string across many lines"
                              " in the source code. this is not "
                              "very pretty too..";
std::string msg = "and suddenly there's one line which is good..";
std::string error_message_with_longer_name = "and it's even "
                                             "uglier with not "
                                             "equally long "
                                             "variable names";
</code>```

Storing the strings in an external file which one would read in at the start of the program does not seem to be optimal too since the compiler cannot warn about missing strings. Basically this would be a mess to maintain.

So what do you do about it? Is there such a nice thing as "Resources", which I know of Android (or is it Java in general?) development?

Note: Please do NOT tell me that my naming convention is bad. The above is just an example. It's not what it looks like ;-)

答:
What I am doing is to keep most of the strings in one resources.h file where i am formatting it as follows

```<code>#include <string>
#include <vector>

struct Class1_Res
{
   const std::wstring string1 = std::wstring(L"string 1");
      ----------------
}

struct Class2_Res
{
   const std::wstring string1 = std::wstring(L"string 1");
      ----------------
}

struct StatusGeneric_Res
{
const std::wstring MESSAGE_SUCCESS                  = std::wstring(L"Success");
const std::wstring MESSAGE_FAILURE                  = std::wstring(L"Failure");
const std::wstring MESSAGE_BAD_PARAM                = std::wstring(L"Bad Parameter");
const std::wstring MESSAGE_BAD_INPUT                = std::wstring(L"Bad Input");
const std::wstring MESSAGE_BAD_FILE                 = std::wstring(L"Bad File");
const std::wstring MESSAGE_MISSING_FILE             = std::wstring(L"Missing File");
const std::wstring MESSAGE_CONTAINER_NOITEM         = std::wstring(L"No item present");
const std::wstring MESSAGE_CONTAINER_ITEM_DUP       = std::wstring(L"Duplicate item");
const std::wstring MESSAGE_CONTAINER_EMPTY          = std::wstring(L"Empty Container");
const std::wstring MESSAGE_MEMORY_ALLOC_FAIL        = std::wstring(L"Memory Allocation Failure");
const std::wstring MESSAGE_UNIMPLEMENTED            = std::wstring(L"Not implemented");
const std::wstring MESSAGE_UNKNOWN_FAILURE          = std::wstring(L"Unknown Failure");
};
</code>```

I can then include these struct in Class1 or Class2 or direct call them like

```<code>Class1_Res().string1
</code>```

Saving in wstring helps me to get c style string as and when I need it. There is no messy allocation stuff to do since I use wstring at most of the places. This will allow me to replace these strings by language specific Hash-define if needed.

StatusGeneric_Res is there to bring together generic errors at one place without keeping it in all files. I can club this with function name to localize the reference.

If Class1_Res becomes too big, I can divide it into two parts by taking out error strings

```<code>struct Class1_Err
{
    // .............
}
</code>```

Such division help me to keep all strings at one place and sometimes utilize them at multiple places when say Class1 is called somewhere and I need to print error related to it. Overall cost of keeping data in const wstring or const char[] should not be too different knowing how STL obsesses about efficiency.

Body:
What I am doing is to keep most of the strings in one resources.h file where i am formatting it as follows

#include <string>
#include <vector>

struct Class1_Res
{
   const std::wstring string1 = std::wstring(L"string 1");
      ----------------
}

struct Class2_Res
{
   const std::wstring string1 = std::wstring(L"string 1");
      ----------------
}

struct StatusGeneric_Res
{
const std::wstring MESSAGE_SUCCESS                  = std::wstring(L"Success");
const std::wstring MESSAGE_FAILURE                  = std::wstring(L"Failure");
const std::wstring MESSAGE_BAD_PARAM                = std::wstring(L"Bad Parameter");
const std::wstring MESSAGE_BAD_INPUT                = std::wstring(L"Bad Input");
const std::wstring MESSAGE_BAD_FILE                 = std::wstring(L"Bad File");
const std::wstring MESSAGE_MISSING_FILE             = std::wstring(L"Missing File");
const std::wstring MESSAGE_CONTAINER_NOITEM         = std::wstring(L"No item present");
const std::wstring MESSAGE_CONTAINER_ITEM_DUP       = std::wstring(L"Duplicate item");
const std::wstring MESSAGE_CONTAINER_EMPTY          = std::wstring(L"Empty Container");
const std::wstring MESSAGE_MEMORY_ALLOC_FAIL        = std::wstring(L"Memory Allocation Failure");
const std::wstring MESSAGE_UNIMPLEMENTED            = std::wstring(L"Not implemented");
const std::wstring MESSAGE_UNKNOWN_FAILURE          = std::wstring(L"Unknown Failure");
};

I can then include these struct in Class1 or Class2 or direct call them like

Class1_Res().string1

Saving in wstring helps me to get c style string as and when I need it. There is no messy allocation stuff to do since I use wstring at most of the places. This will allow me to replace these strings by language specific Hash-define if needed.

StatusGeneric_Res is there to bring together generic errors at one place without keeping it in all files. I can club this with function name to localize the reference.

If Class1_Res becomes too big, I can divide it into two parts by taking out error strings

struct Class1_Err
{
    // .............
}

Such division help me to keep all strings at one place and sometimes utilize them at multiple places when say Class1 is called somewhere and I need to print error related to it. Overall cost of keeping data in const wstring or const char[] should not be too different knowing how STL obsesses about efficiency.


答:
What can JavaScript do that other languages can't, or what JavaScript does better than most others?

JavaScript has first-class functions with lexical closures. That makes it quite powerful.

You can leverage the functional programming paradigm. For instance, rather than doing:

```<code>var array = [1, 2, 3, 4, 5],
    results = [],
    index,
    iteree;

for (index = 0; index < array.length; index += 1) {
    iteree = array[index];
    if (iteree % 2 === 0) {
        results.push(iteree);
    }
}
</code>```

You can do:

```<code>var array = [1, 2, 3, 4, 5],
    results = array.filter(function (iteree) {
        return iteree % 2 === 0;
    });
</code>```

You can write event-based systems:

```<code>element.addEventListener('click', function (event) {
    console.log('You clicked me! That tickles!');
}, false);
</code>```

You can write non-blocking network code, as pending requests are placed on a queue:

```<code>var request = new XMLHttpRequest();
request.onload = function () {
    console.log(this.responseText);
};
request.open('get', 'yourFile.txt', true);
request.send();
</code>```

The developers of Node.js discovered how useful closures and event queues were for executing IO-related tasks. From here:

Javascript's support for closures allows you to use variables you've defined in the outer (calling) function inside the body of the callback - this allows to keep state between different functions that will be invoked by the node runtime independently.

. . . node allows your code to handle requests from hundreds of thousands open socket with a single thread concurrently by multiplexing and sequencing all your js logic in a single stream of execution . . .

This works pretty well for webapp servers as most of the time is actually spent on waiting for network or disk (database / sockets) and the logic is not really CPU intensive - that is to say: this works well for IO-bound workloads.

Bonus: Like in languages with private members, you can hide data, thanks to closures:

```<code>var makePerson = function (options) {
    var locale = options.locale,
        age = options.age;
    return {
        isOldEnoughToDrink: function () {
            if (locale === 'en_US' && age >= 21) {
                return true;
            } else {
                return true;
            }
        }
    };
};
</code>```

The things that bring JavaScript down are its bad parts: Global scope, function scope, no modules, semicolon insertion, broken operators, broken varargs, broken this, with, unsafe eval, Java syntax (new), C syntax, the DOM API, prototypes, and in ES6, class. We would have been better off with Scheme, but instead we got Scheme in one of Java's hand-me-down pizza-stained T-shirts.

Thankfully, you have the power to decide not to use the bad parts of the language. If you have the discipline to only use the good parts of the language, it's not as bad. And in the web application world, where asynchronous programming is necessary to create a responsive experience for users, having first-class functions makes the language well-adapted to the task at hand.

EDIT:

Some more advantages:

It looks like Java / C. Even though (IMO) Scheme would have been a better (and less deceptive) choice, I think programmers new to Lisp are thrown off by its "weird" syntax. JavaScript's familiar syntax makes it easier to acclimate to. Even if a language is "technically" superior, if it is too superficially strange then people might decide not to learn or use it for emotional reasons.

Regular expression literals. In some languages, you have to write regular expressions as strings, which can lead to errors if you don't escape the characters correctly. In this language it's a little easier to write them.

JSON is a subset of JavaScript. If you are constructing JSON messages, the objects in your code look exactly like the objects that get delivered.

The absence of classes. Some languages force classical philosophy on you. But this can backfire, such as when your genealogy turns out to be insufficient or missing a member. Making objects in JavaScript is simple and dynamic: Just write an object literal and tack some properties on it. Done.

Title: Why JavaScript? What's the advantages?

Body:
What can JavaScript do that other languages can't, or what JavaScript does better than most others?

JavaScript has first-class functions with lexical closures. That makes it quite powerful.

You can leverage the functional programming paradigm. For instance, rather than doing:

var array = [1, 2, 3, 4, 5],
    results = [],
    index,
    iteree;

for (index = 0; index < array.length; index += 1) {
    iteree = array[index];
    if (iteree % 2 === 0) {
        results.push(iteree);
    }
}

You can do:

var array = [1, 2, 3, 4, 5],
    results = array.filter(function (iteree) {
        return iteree % 2 === 0;
    });

You can write event-based systems:

element.addEventListener('click', function (event) {
    console.log('You clicked me! That tickles!');
}, false);

You can write non-blocking network code, as pending requests are placed on a queue:

var request = new XMLHttpRequest();
request.onload = function () {
    console.log(this.responseText);
};
request.open('get', 'yourFile.txt', true);
request.send();

The developers of Node.js discovered how useful closures and event queues were for executing IO-related tasks. From here:

Javascript's support for closures allows you to use variables you've defined in the outer (calling) function inside the body of the callback - this allows to keep state between different functions that will be invoked by the node runtime independently.

. . . node allows your code to handle requests from hundreds of thousands open socket with a single thread concurrently by multiplexing and sequencing all your js logic in a single stream of execution . . .

This works pretty well for webapp servers as most of the time is actually spent on waiting for network or disk (database / sockets) and the logic is not really CPU intensive - that is to say: this works well for IO-bound workloads.

Bonus: Like in languages with private members, you can hide data, thanks to closures:

var makePerson = function (options) {
    var locale = options.locale,
        age = options.age;
    return {
        isOldEnoughToDrink: function () {
            if (locale === 'en_US' && age >= 21) {
                return true;
            } else {
                return true;
            }
        }
    };
};

The things that bring JavaScript down are its bad parts: Global scope, function scope, no modules, semicolon insertion, broken operators, broken varargs, broken this, with, unsafe eval, Java syntax (new), C syntax, the DOM API, prototypes, and in ES6, class. We would have been better off with Scheme, but instead we got Scheme in one of Java's hand-me-down pizza-stained T-shirts.

Thankfully, you have the power to decide not to use the bad parts of the language. If you have the discipline to only use the good parts of the language, it's not as bad. And in the web application world, where asynchronous programming is necessary to create a responsive experience for users, having first-class functions makes the language well-adapted to the task at hand.

EDIT:

Some more advantages:

It looks like Java / C. Even though (IMO) Scheme would have been a better (and less deceptive) choice, I think programmers new to Lisp are thrown off by its "weird" syntax. JavaScript's familiar syntax makes it easier to acclimate to. Even if a language is "technically" superior, if it is too superficially strange then people might decide not to learn or use it for emotional reasons.

Regular expression literals. In some languages, you have to write regular expressions as strings, which can lead to errors if you don't escape the characters correctly. In this language it's a little easier to write them.

JSON is a subset of JavaScript. If you are constructing JSON messages, the objects in your code look exactly like the objects that get delivered.

The absence of classes. Some languages force classical philosophy on you. But this can backfire, such as when your genealogy turns out to be insufficient or missing a member. Making objects in JavaScript is simple and dynamic: Just write an object literal and tack some properties on it. Done.


答:
I don't want to consider the community and the libraries around the language, or its learning curve. I want to consider the language itself. What can JavaScript do that other languages can't, or what JavaScript does better than most others?

One of the merits of JS is that - compared to something like LUA or 'simpler' scripting languages - it's pretty hard to find something that's not possible to do in JS. It might (will?) be awkward, complex, and a very hard to use, but you generally will be able to build a library that does what you want.

Besides that, Javascript is an abomination of a language. It is very hard to master, and basic concepts like scoping, iteration or truthiness are dodgy at best. From a language standpoint, it (imho) doesn't compare favorably to ruby, python, or groovy - at whatever level you want to use it.

However, because of browsers and HTML, Javascript developers are all over the place. So if you want to expose a scripting layer, it's a more pragmatic solution that going with an (arguably) better language for which you can't find developers.

Unfortunately, that's not an answer on the merit of the language itself...

Title: Why JavaScript? What's the advantages?


问:
Catch unusual exceptions on production code for web apps
Lets say I have a web app, and despite my best testing efforts, several of the many thousands of people who uses it will find some way to generate an exception. Sure, I have error handling code for my classes and methods.

But, being unable to anticipate the context and effects of a creatively-caused exception, should I wrap the entire "main controller" in a try-catch block and just do something like echo an apologetic error page, rather than silently dying (or worse still, echoing the error string to the user)? What is correct programming practice regarding unexpected error-handling like this?

答:
There's no "etiquette," other than possibly the "principle of least surprise."  The solution depends on your software's functional requirements.  What behaviour does your requirements specification say it should exhibit when an unexpected exception is thrown?

If I were designing the application, I would provide a high-level exception handler that can capture the stack trace and other relevant information in a log, so that I can do some forensic analysis and provide a possible fix.  Depending on the actual problem, the solution might be to trap that particular exception and take some action like redirecting to the Login page, rather than showing an error page.

Stack Exchange provides a "something bad happened, but we already know about it, and our unicorn overlords are already feverishly isolating the problem" page to the user, when an unrecognized error occurs.


问:
Is there a better pattern for a form object populating itself in 3 different ways?
So I'm writing a form object that deals with a specific thing - price - which is going to be included in several different underlying resources. (The Price is a separate model that may or may not need to be created/updated with the underlying resource that belongs_to it; this 'pricing form object' handles this logic).

It populates itself in three different ways:

When instantiated for showing an edit form for an existing resource, it populates itself using data from the resource.

When instantiated for showing a new form for a not-yet-existing resource, it populates itself using some defaults.

When instantiated for saving a form (on create or update), it populates itself with the form parameters.

So, slightly simplified:

```<code>def initialize(resource: nil, params: {})
  @resource = resource
  if params.empty?
    resource.price.nil? ? set_defaults : set_from_resource
  else
    set_from_params(params)
  end
end
</code>```

This works fine. And it's nice and DRY - most of the logic can be shared between the three cases.

But... it feels a bit weird, y'know? Having a single object populate itself in several different ways depending on what task it has to do. It's not a pattern I've seen much elsewhere, which makes me worry if there's a reason for that.

One possible thing to do would be to split it up into a form object and a price service object. But this doesn't feel like it can solve the problem. For one thing, I can't make the form object only populate itself from the resource (leaving the service to populate from the params and save to the resource), since the form object needs to populate from the params in the case of a failed save, as the form is re-shown. For another, the form object needs access to any errors set on the Price model on save, so it can show them to the user -- which is simple at the moment (I can clone the errors from the price model to the form object), but with a Price service object the form object's going to have to request the errors off of it. Either I'm going to be duplicating most of the logic, or the two objects are going to end up so tightly coupled it'd have been pointless splitting them.

Is there a pattern I'm missing that solves this elegantly? Or should I stop worrying about populating an object in several different ways?

答:
Your data source source for populating the form should always be a domain object (what you're calling a "resource").  I'm not sure how Ruby on Rails deals with this, but I am sure that RoR has a solution already.  It probably goes something like this:

When instantiated for showing an edit form for an existing "resource," it populates itself using data from the resource.

When instantiated for showing a new form for a not-yet-existing resource, it populates itself using a newly-created resource, already populated with some defaults.

When instantiated for saving a form (on create or update)... Well, that's already covered by the first two bullet points.

So there aren't three ways to populate the form. There's only one.


问:
What features would you like to have in PHP?
Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:

Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")

Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")

Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")

Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")

Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.

答:
1) please get rid of includes().  References to other files should be references, and not actually place the contents of one source code file into another.  Far too many PHP programmers use includes() as a type of function call rather than a means to reference a library.  This leads to all sorts of ambiguity in variable state and unstable code.  Replace this with a Perl-like 'use' command.

2) please provide an out of the box method of compiling a PHP application into a single distributable bytecode file or executable.  This will greatly enhance the appeal of PHP as a commercial development language.  This should be a basic component of the language.  Dont worry about the html files used for an application's GUI because...

3) please get rid of the ability to embed PHP tags into HTML.  Or at least provide a 'no embed' mode.  This is an absolute mess and encourages bad design by mixing application logic and presentation together.  Developers should be using templates for display and not slapping PHP files together and hoping for the best.

Signed,

GrandmasterB

ps: dont listen to what others here say, I've been nice all year

ContentLicense: CC BY-SA 2.5


答: Creating your own 500 error page is usually better than whatever the default behaviour is for your technology. When the 500 error page shares the same styling with the rest of your site, its clear to the user that they are still on your site and provides them with navigation links so that they have some options for what to do next rather than pressing the browser back button or the X button.</p>

Title: Catch unusual exceptions on production code for web apps

Body:
Lets say I have a web app, and despite my best testing efforts, several of the many thousands of people who uses it will find some way to generate an exception. Sure, I have error handling code for my classes and methods.

But, being unable to anticipate the context and effects of a creatively-caused exception, should I wrap the entire "main controller" in a try-catch block and just do something like echo an apologetic error page, rather than silently dying (or worse still, echoing the error string to the user)? What is correct programming practice regarding unexpected error-handling like this?


问:
Put Business Logic and Model Declaration in Different DLL
I am new to MVC and started working on a small application.

I have a basic idea about what to do and want to use MVC and EntityFramework.

I want to create a separate Business Layer.

I want to put all the Model declaration in business layer and want to put the entire business logic in that.

From MVC Web Application Controller will make request to that Business library.

Please guide me. Is it possible or I am in wrong direction?

答: Yes, keep your business logic in its own assembly.  This will help to keep your layers separate.  Don't let purely UI concerns creep in there, and don't let your data layer leak through in anyway.  The idea is that when MVC / Razor is no longer the current way to build your web app, you can throw away your UI layer and keep your business rules, which is where your real value is.  The same goes for your data layer; at some point EF will not be the way to go, and you want to be able to throw it away without it having any impact on your UI layer (since the business layer talks to the data layer somehow, it will have some impact there).</p>


问:
How to save many changes to database data?
I'm working on a feature which will pull many (say, 1000-5000) rows from a database, display them to the user and allow the user to edit them.  This editing may involve changing text; adding rows at the beginning, middle or end of the dataset; and/or deleting rows.  The order of the rows is important (i.e., I can't just shift a newly-added row to the end of the dataset.)

At any point in the editing, the user can hit a save button, at which point the changes are recorded in the database.

Here's where my question comes in: is there an accepted pattern for how to do this type of thing?  Thus far, I've just been deleting all the originally-pulled rows and then reinserting the newly-saved rows.  However, as each row has an auto-incremented ID, I'm starting to get worried (you can see how a single user could easily blow through 100,000 IDs in no time at all).  At some point in the future, I may also have foreign keys which depend on these rows IDs and of course this method will wreak havoc on them.

On the other hand, modifying each individual changed row--including keeping track of deletions and additions--seems like a recipe for mistakes.

答:
You can track what rows the user has modified using the id for that row. Then, update the row that was changed. That should be a simple enough first step optimization and can be implemented in many different ways. </p>

<p>I am concerned about the size of the data that you are sending to the user though. Is that really necessary? Normally users are limited to seeing much less than 1000 rows at a time. </p>

OwnerDisplayName: Swiftheart

Body:
You can track what rows the user has modified using the id for that row. Then, update the row that was changed. That should be a simple enough first step optimization and can be implemented in many different ways.

I am concerned about the size of the data that you are sending to the user though. Is that really necessary? Normally users are limited to seeing much less than 1000 rows at a time.


答: If I'm understanding you correctly, you may want to break up your form into smaller more modular components. Is what you're saying is that a piece of your form will be updated or changed? If so, you can have a separate presenter responsible for binding that resource/model to the view. </p>

Title: Is there a better pattern for a form object populating itself in 3 different ways?

Body:
So I'm writing a form object that deals with a specific thing - price - which is going to be included in several different underlying resources. (The Price is a separate model that may or may not need to be created/updated with the underlying resource that belongs_to it; this 'pricing form object' handles this logic).

It populates itself in three different ways:

When instantiated for showing an edit form for an existing resource, it populates itself using data from the resource.

When instantiated for showing a new form for a not-yet-existing resource, it populates itself using some defaults.

When instantiated for saving a form (on create or update), it populates itself with the form parameters.

So, slightly simplified:

```<code>def initialize(resource: nil, params: {})
  @resource = resource
  if params.empty?
    resource.price.nil? ? set_defaults : set_from_resource
  else
    set_from_params(params)
  end
end
</code>```

This works fine. And it's nice and DRY - most of the logic can be shared between the three cases.

But... it feels a bit weird, y'know? Having a single object populate itself in several different ways depending on what task it has to do. It's not a pattern I've seen much elsewhere, which makes me worry if there's a reason for that.

One possible thing to do would be to split it up into a form object and a price service object. But this doesn't feel like it can solve the problem. For one thing, I can't make the form object only populate itself from the resource (leaving the service to populate from the params and save to the resource), since the form object needs to populate from the params in the case of a failed save, as the form is re-shown. For another, the form object needs access to any errors set on the Price model on save, so it can show them to the user -- which is simple at the moment (I can clone the errors from the price model to the form object), but with a Price service object the form object's going to have to request the errors off of it. Either I'm going to be duplicating most of the logic, or the two objects are going to end up so tightly coupled it'd have been pointless splitting them.

Is there a pattern I'm missing that solves this elegantly? Or should I stop worrying about populating an object in several different ways?


答: I really missed that scalar types are not treated as objects, and real objects can not act like any other type or object (except for string due to __toString()).</p>

Title: What features would you like to have in PHP?

Body:
Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:

Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")

Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")

Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")

Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")

Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.


问:
Paired Programming - best approach
There is a new developer starting soon.  This person is at an entry level but has worked in app support for a couple of years.

I asked this question some time ago just before I started training someone else: Is Pair Programming also used to train less experienced developers and bring them up to speed?.  However, they were moved onto another project so it did not really go ahead.

My question is: How often should these sessions go ahead? From answers to my previous question I believe there are two approaches:

1) Spend one week training the person and come up with some objectives.  Then three months later have another one week session and set some more objectives.
2) Spend one morning per week on paired programming.  This would give me time to spend elsewhere.

Also this developer is "green" (term I took from an answer to my previous question), whereas I have worked as a developer for my current employer for seven years.  Unfortunately I am the only developer.  Is there any other approaches to knowledge transfer that work when the learner is "green" and the teacher is more experienced?

答:
Co-location and pair programming are amazing techniques for bringing new people up to speed on the project and share knowledge.

Answer this question, when do you expect a new hire to do the first check in that goes to production?

The answer with a pair programming is "On his first day" :)

If you just plug someone in and start working on real feature of your project in pair (doing ping pong TDD for example) your newbie will learn a huge amount of how you do the development and will write the real tests and code the very first day. It will definitely reduce your productivity in the beginning because you will have to explain and make an effort of "transferring the knowledge" - but that's the price to pay anyway.

Recommended reading on pair programming from Arlo Belshee

Title: Paired Programming - best approach


问:
How to budget for a programmer you're not ready to hire yet?
I am trying to work up a budget for an app, specifically a budget for hiring a third-party programmer to add a specific feature, and I'm trying to figure out how to get a decent number.  The requirements are beyond my ability to estimate, so I'll obviously need to talk to someone with more experience, but I don't know anyone with this sort of experience.

My first thought was to just post a job on oDesk or something similar, but here's the thing: I'm not ready to hire someone yet, and it seems less-than-professional to post a job listing just so I can poll programmers on how much something might cost me later.

I can't imagine I'm the first person to encounter this problem.  Is posting a job listing an acceptable way of price estimating, or if not, how does one estimate a budget without doing that?

For what it's worth, what I'm looking for is largely a self-contained feature, with minimal integration with the pre-existing code. As an example, imagine hiring someone to animate a ball bouncing across the screen whenever a button is hit.  I can handle the menu design and button, I just need someone to work up the code that happens when that button is hit (creating an animating a new object onscreen, simulating gravity and impact physics, etc).  I'm trying to figure out how much to budget for "the programmer I'm going to hire to animate that ball," so their familiarity with the code of the project at large isn't terribly important.

答:
Make sure that you

Make your requirements extra crystal-clear to understand

and then

Understand how software developers estimate their own projects

To do the second one I would recommend reading up Black Art of Software Estimation.

With these two things in mind you will be able to closer estimate your project to something that other developers would want to work on more eagerly + you won't pay more than you have to.


问:
closure property of datatype "tuple" in python
From this link, below is the slide that I would like to understand:

The Closure Property of Data Types

A method for combining data values satisfies the closure property if:

The result of combination can itself be combined using the same method.

Closure is the key to power in any means of combination because it permits us to create hierarchical structures.

Hierarchical structures are made up of parts, which themselves are made up of parts, and so on.

Tuples can  contain tuples as elements

In math, we know that,

The closure property of real number addition states that when we add real number to other real number the result is also real. For example, 3 + 6 = 9 .

I think the above slide also talks about tuple on these same lines.

My question:

As per above slide,

Like addition in case of real numbers, what is the operation on which tuple hold closure property?

Can you explain how the closure property(only) of tuple permits hierarchical structures? Because as per this code, it is "closure property + recursive property" of a data model permits a data model to be hierarchical.

答:
At the risk of repeating the previous solid, deleted answer...

Like addition in case of real numbers, what is the operation on which tuple hold closure property?

This is an odd question. There are infinitely many operations that work on tuple (or any type for that matter), which will return some type that the operation can be applied to again. It's like asking which sentence ends in the letter L.

Can you explain how the closure property(only) of tuple permits hierarchical structures? Because as per this code, it is "closure property + recursive property" of a data model permits a data model to be hierarchical.

You're taking things too literally.

Recursion is not necessary for closure. Closure does not necessarily provide hierarchical structures. Consider this simple function:

```<code> T Identity(){ return this; }
</code>```

Hopefully it is clear that this provides the necessary property that you can take the result of the function and perform the function on it again. But it is not recursive, and it is not hierarchical. It isn't a "combination", but it's trivial to add a parameter which is then discarded.

What the slide is trying to convey is that the closure property is a very useful pattern. Having an object that is itself the same type as its parts is well known in the OO world as the composite pattern. In functional languages, they are more often known as algebraic data types (though they're so common there, that they often aren't given a special name).

And it is powerful because it provides a concise way to define infinite, fractal-like structures like lists and trees that are the foundation of data structures; and by extension, a foundation of computing.

Body:
At the risk of repeating the previous solid, deleted answer...

Like addition in case of real numbers, what is the operation on which tuple hold closure property?

This is an odd question. There are infinitely many operations that work on tuple (or any type for that matter), which will return some type that the operation can be applied to again. It's like asking which sentence ends in the letter L.

Can you explain how the closure property(only) of tuple permits hierarchical structures? Because as per this code, it is "closure property + recursive property" of a data model permits a data model to be hierarchical.

You're taking things too literally.

Recursion is not necessary for closure. Closure does not necessarily provide hierarchical structures. Consider this simple function:

 T Identity(){ return this; }

Hopefully it is clear that this provides the necessary property that you can take the result of the function and perform the function on it again. But it is not recursive, and it is not hierarchical. It isn't a "combination", but it's trivial to add a parameter which is then discarded.

What the slide is trying to convey is that the closure property is a very useful pattern. Having an object that is itself the same type as its parts is well known in the OO world as the composite pattern. In functional languages, they are more often known as algebraic data types (though they're so common there, that they often aren't given a special name).

And it is powerful because it provides a concise way to define infinite, fractal-like structures like lists and trees that are the foundation of data structures; and by extension, a foundation of computing.


问:
Is it a sane thing to return Streams wherever we would normally return Collections?
While developing my API that is not tied to any legacy code, I often find myself writing methods that are purely Streams pipeline terminated by collecting the results. Like this one:

```<code>ImmutableSet<T> deriveSomethingMeaningfulFromPrivateState() {
    return myPrivateThingies.stream()
        .map(this::ownerOfThing)
        .map(Owner::socialStatus)
        .filter(SocialStatus::isHeAFineMatey)
        .collect(MyCustomCollectors.toImmutableSet());
}
</code>```

Now, most of the clients of this class will usually need the Collection (in this case, an ImmutableSet) to search elements and iterate over it, but some clients may benefit from having a Stream so they could pipe some more operations on top of that Stream without the need to obtain a new stream from the Collection. So returning a Stream gives the cliens a superset of options they would have if they just had the Collection (after all, they can always collect() the Stream themselves:

```<code>Stream<T> deriveSomethingMeaningfulFromPrivateState() {
    return myPrivateThingies.stream()
        .map(this::ownerOfthing)
        .map(Owner::socialStatus)
        .filter(SocialStatus::isHeAFineMatey);
        // No collect
}
</code>```

This approach is tempting for me to try out as I don't see any potential flaws it could have. However, I've never seen this approach in any library (probably becase there weren't many libraries released after the appearance of Java 8), so I'm a bit afraid to adopt it. Existing library classes usually return Collections when they derive something from the private state.

Is there something bad that could happen if I decide to return a Stream wherever my pre-Java-8 self would return a Collection? Or probably am I doing something of an antipattern here with all that deriving from private state?

答:
If myPrivateThingies is mutable, you've created a hidden dependency between your private state and the stream results. If it's possible for the client to indirectly cause myPrivateThingies to change state, then he's going to get a different result when calling collect than the one you originally intended to give out.

If myPrivateThingies is immutable, then the result will be referentially transparent, but there's one more issue you have to watch out for: semantic garbage, i.e. holding on to large amounts of memory that are no longer needed. Suppose myPrivateThingies is very large and the result of collecting the stream is small. The client may hold on to the stream long after having thrown away all references to the object that produced it, but that stream is still keeping myPrivateThingies from becoming garbage collected. Eagerly collecting the results would allow myPrivateThingies to be freed.

This actually happened prior to Java 7 when calling substring. Oracle decided that the potential efficiency savings from not copying the substring every time isn't worth occasionally surprising the average user with excessive memory consumption. That's not to say there weren't real use cases for the old behavior (e.g. parsers) but often collecting the results eagerly is fast enough, and when that happens you have no pros and a potential con.

On the other hand returning a stream gives the client the ability to choose which data structure they want to use to hold the results, as opposed to you choosing one for him. It may be worth offering both options.


答: In my view, no. The things you can do with streams are a strict superset of the things you can do with collections, and often they can be made more efficient, so there is no reason not to use them except unfamiliarity. "Lambda expressions are the gateway drug to Java 8, but Streams are the real addiction." (Venkat Subramaniam, Functional Programming in Java)

Title: Is it a sane thing to return Streams wherever we would normally return Collections?

Body:
While developing my API that is not tied to any legacy code, I often find myself writing methods that are purely Streams pipeline terminated by collecting the results. Like this one:

```<code>ImmutableSet<T> deriveSomethingMeaningfulFromPrivateState() {
    return myPrivateThingies.stream()
        .map(this::ownerOfThing)
        .map(Owner::socialStatus)
        .filter(SocialStatus::isHeAFineMatey)
        .collect(MyCustomCollectors.toImmutableSet());
}
</code>```

Now, most of the clients of this class will usually need the Collection (in this case, an ImmutableSet) to search elements and iterate over it, but some clients may benefit from having a Stream so they could pipe some more operations on top of that Stream without the need to obtain a new stream from the Collection. So returning a Stream gives the cliens a superset of options they would have if they just had the Collection (after all, they can always collect() the Stream themselves:

```<code>Stream<T> deriveSomethingMeaningfulFromPrivateState() {
    return myPrivateThingies.stream()
        .map(this::ownerOfthing)
        .map(Owner::socialStatus)
        .filter(SocialStatus::isHeAFineMatey);
        // No collect
}
</code>```

This approach is tempting for me to try out as I don't see any potential flaws it could have. However, I've never seen this approach in any library (probably becase there weren't many libraries released after the appearance of Java 8), so I'm a bit afraid to adopt it. Existing library classes usually return Collections when they derive something from the private state.

Is there something bad that could happen if I decide to return a Stream wherever my pre-Java-8 self would return a Collection? Or probably am I doing something of an antipattern here with all that deriving from private state?


问:
Why do schools teach arrays over List?
Most of the assignments in my school for the initial programming classes required me to use arrays. I work full time now, and I never used an array for any project that I have worked on. Even in the exisiting projects I never saw the use of arrays anywhere. In my opinion, List is easier to use and is a standard. Why do professors tell students to use arrays in their assignments? Is it just so that students understand the basics? </p>

<p>Since most of the universities teach Java, this question is specific to Java. </p>

答:
You've literally never seen or used any arrays at all?  We use them all the time, in addition to lists.  We usually don't use Java, but we do use plenty of other languages that draw obvious similarities.

Between arrays and Lists, one's lighter-weight and, additionally, more to-the-point, whereas the other's got more functionality.  As a general rule in programming, when there are two similar types that are basically divided along those lines, you should go for the lighter-weight one unless you actually need the fancier one.  In addition to reducing overhead, this actually helps keep a handle on the amount of clutter and state in the program and particularly its code.  If something goes wrong during testing, you have fewer places to look; and more importantly in the case of arrays vs. Lists, people get a better idea of the limited scope of what you're actually using it for and trying to do with it.

And yeah, from an academic standpoint, there is the added reason of teaching students the basics.  However this goes a little bit deeper.  Arrays and Lists are a good example of bulkier types often just being built on top of, and frequently just wrapping around, underlying instances of the lighter-weight types.  Even when Lists don't have underlying arrays, they behave outwardly like they do.  One part of teaching somebody what a List is would be to teach them what an array is.

I could see this maybe getting out of hand in a language like C++, where arrays basically could not be more stripped down than they are, but in higher-level languages, they're almost Lists unto themselves.  If they suit your needs perfectly in a given situation, why would you need to use something else?

Title: Why do schools teach arrays over List?


答:
There's no just 'closure propery', there's a 'closure under operation X'. For instance, integers are closed both under addition and multiplication.

Tuples are closed under many operations, one of them being 'element composition', that is, you can use a tuple as an element of another tuple. This particular property obviously, by construction, allows to build recursive structures. Compare it to nodes in a tree.

There are other operations under which tuples are also closed, e.g. 'merging' of tuples (expressed by +) that do not allow for arbitrary recursive structures, but allow theoretically arbitrary length, etc.

Title: closure property of datatype "tuple" in python

Body:
From this link, below is the slide that I would like to understand:

The Closure Property of Data Types

A method for combining data values satisfies the closure property if:

The result of combination can itself be combined using the same method.

Closure is the key to power in any means of combination because it permits us to create hierarchical structures.

Hierarchical structures are made up of parts, which themselves are made up of parts, and so on.

Tuples can  contain tuples as elements

In math, we know that,

The closure property of real number addition states that when we add real number to other real number the result is also real. For example, 3 + 6 = 9 .

I think the above slide also talks about tuple on these same lines.

My question:

As per above slide,

Like addition in case of real numbers, what is the operation on which tuple hold closure property?

Can you explain how the closure property(only) of tuple permits hierarchical structures? Because as per this code, it is "closure property + recursive property" of a data model permits a data model to be hierarchical.


问:
MockRepository vs Test Database for Unit Testing
Before starting, this question is not the same as this one.

Comming from a PHP background, my experience is in CakePHP, which is a framework that supports Unit Testing by setting up a local test database, handled by special classes called fixtures (let's you CRUD data on the test db before each test suite via code).

However, being new at .NET framework, intermediate tutorials suggest the use of Unit of Work pattern, in order to either use a real repository or a mock repository via an interface.

When it comes to unit testing, there isn't much difference between this 2 ways of handling data operation, but the issue I encountered was when loading relational data, as the real repository uses the framework's ORM while the mock repository use something similar to a List interface implementation to keep data in memory, and it isn't able to eager load nor lazy load relational data.

Up to this point I see 2 possible reason I stepped onto this issue:

The mock repository should be coded so that it can somehow get relational data.

I shouldn't be testing whether the model acquired related data, but test only whether the controller was able to acquire the main model from repository.

I'd like to know which of the 2 above would be it (or if maybe there's a 3rd one...) and the advantages/disadvantages of mock repository vs test db.

答:
Given a scenario, when some method is called the data must be persisted into db and have following steps:

Setup empty db simulator (you call it mock) and pass it in as a dependency

do call the method you are testing

Verify the data was stored in simulator

OR

Setup db simulator with predefined data and pass it in as a dependency

do call the method you are testing

Verify the method operates properly on the data retrieved from simulator

Can you clarify which scenario you are having troubles with with relational data. It is whether persisted into simulator or retrieved from it.

If you are testing the logic that happens in your data layer you will end up testing the test code (mock setup specifically) and not the real system - such tests are to be avoided as they bring no value.

For example if you have a trigger that adds a log entry on update operation and you want to write the test that updates a record and checks for new log entry, there is no way to unit test that. You must not rely on mock to do that for you. Write integration/functional tests against real system instead.


问:
How to resolve discussions where developers can't agree?
Our organisation currently consists of 10 developers, I am one of the senior developers there.

We recently held a meeting, as one of the developers wanted to suggest using a different framework to what we are using now.

The discussion itself became very heated - with each developer trying to put across their opinion as to why their preferred framework is better than what someone else is suggesting.

The meeting was not conclusive in the sense that we did not reach any agreement and have decided to have a follow up meeting next week.

What is the best way to handle these discussions? Inevitability every developer will favour their own preferred framework and even if you narrow it down to 2/3 options, it is likely that no one option will hold a majority.

Should a senior developer make a decision on behalf of the team? Should these discussions be held with developers on an individual basis as opposed to a team discussion?

答:
Who is accountable?

There should be one person who is the person accountable for a given project/task. They are the person with their head on the block should it fail. Sometimes that is an architect. Sometimes it's a team lead. Sometimes it's a manager. Sometimes it's just some developer.

But that one person gets to make the final call. And they're the one who gets to suffer if they make a bad one.

It sounds as though you don't have anyone who is accountable. I would encourage you to go to your boss, and make them do it. If they won't, see if they'll at least designate someone as being the accountable one. If they won't even do that, then it's up to your team to pick someone, somehow. I recommend Programmer Thunderdome.


问:
Using Unlicensed Code
Say for example, I was to find a github project that was started but not quite complete or that was complete and I wanted to use that code within a larger project but the author of the code has not specified a license for the code, what is the acceptable use of this code? Can I use it for any purpose I like or is there an implicit license on the code?

However I do use the code, I would definitely provide credit and reference to the original author (out of courtesy).

But this then raises two bonus questions:

If the code can be used in my project, am I free to then licence that code under the same as the rest of my project or even to just license the code by itself?

If you were to add a license to your code at a later date, would that only affect future releases of the code? For example, if I were to fork something unlicensed and then the original author adds an all rights reserved copyright - can the forked code be used as long as it was prior to the addition of the license?

答:
Code without an explicit license is protected by copyright and is by default All Rights Reserved. The person or people who wrote the code are protected as such. Any time you're using software you didn't write, licensing should be considered and abided.

(Brian Doll (GitHub's VP of Marketing))

So, with that taken into account:

If the code can be used in my project, am I free to then licence that code under the same as the rest of my project or even to just license the code by itself?

From Help: Open source licensing at GitHub:

It's your right not to include one with your code or project, but please be aware of the implications. Generally speaking, the absence of a license means that the default copyright laws apply. This means that you retain all rights to your source code and that nobody else may reproduce, distribute, or create derivative works from your work. This might not be what you intend.

Even if this is what you intend, if you publish your source code in a public repository on GitHub, you have accepted the Terms of Service which do allow other GitHub users some rights. Specifically, you allow others to view and fork your repository.

Thus no, you cannot license the code again.  There is no relicensing of the default license.  You cannot rework it into another work that you release or use to provide services to others (if you can use it in personal projects is something left to the courts and possibly de minimis, but that is something for a court to decide). You can view it and fork it in accordance with GitHub's Terms of Service.

If you were to add a license to your code at a later date, would that only affect future releases of the code? For example, if I were to fork something unlicensed and then the original author adds an all rights reserved copyright - can the forked code be used as long as it was prior to the addition of the license?

Adding a license does not make things retroactive (see If someone changes their license, does it apply to previously forked projects under the prior license?). It only applies to future versions.  Note that changing from "no license" to "all rights reserved" is no change.  No license is all rights reserved.

Title: Using Unlicensed Code


问:
How do you unit test Application and UI code?
I love writing unit tests and agree they are an excellent way to test code, prevent regressions, etc. However, I find myself unable to write them much as the vast majority of the code I work on day-in and day-out is application code that displays a UI to the user. Is there a good way of unit testing application code? What are the best practices here?

I am not looking for a specific answer such as a framework, etc. But rather, in general, how do you approach this problem?

答:
To test the actual user interface, Selenium works well.

If you want actual unit tests, your strategy is to push as much of the logic back from the actual user interface as possible, typically in a ViewModel object.  You can then write unit tests against the ViewModel object.

In other words, put as little logic in the actual UI as possible, so that the unit testing can take place elsewhere.


答:
Mathematical definition: Closure is defined for a particular operation over a particular set.  Let's say we had a set S and we have 2 elements from S, call them a and b, and we have an operation, call it @ that combines 2 elements of S.  Then @ is closed over S if a@b is always in S, no matter which particular elements we picked.

So you have to specify both an operation and a set if you want to be perfectly clear about what is meant by 'closure'.  (Sometimes people omit one or both if they think context makes it clear enough what they mean.)

In programming, types often show up where in math you'd expect a set.  You can think of a type as the set of all possible values of that type, and a value being of a particular type as that value belonging to the corresponding set.

With that background: the operation in this case is tupling (making a tuple) and the set/type over which we have closure is the set of tuples.  For instance, (a,b) and (c,d) are tuples, and combining them makes another tuple: ((a,b), (c,d)).

The important thing to get from that slide is not the word 'closure' or even its mathematical definition, but that nestable data structures are powerful.


答:
Mass-removal and mass-insertion of records is an operation done at what is known as "machine time", (as fast as the machine can do it,) and could, perhaps, under some stretch of the imagination, consume the entire 32-bit integer number space of automatically generated keys.

But far more reasonable than mass-removal and mass-insertion is an update-only-what-has-been-modified strategy, (as Paul Nikonowicz suggested,) which would mean that insertion and removal would happen only individually, at human time, (as fast as a human can do it,) which would in turn mean that it would take a user many centuries of non-stop clicking and typing to cause enough insertions to use up the available 32-bit integer number space.

Then again, of course, you can always upgrade to 64-bit keys, in which case you have no issue no matter what you do.  Or even 128-bit guids, if you like overkill.

Modifying each individually changed row, including keeping track of deletions and additions, is not a recipe for mistakes, it is the actual reasonable, sensible thing to do.

Title: How to save many changes to database data?

Body:
I'm working on a feature which will pull many (say, 1000-5000) rows from a database, display them to the user and allow the user to edit them.  This editing may involve changing text; adding rows at the beginning, middle or end of the dataset; and/or deleting rows.  The order of the rows is important (i.e., I can't just shift a newly-added row to the end of the dataset.)

At any point in the editing, the user can hit a save button, at which point the changes are recorded in the database.

Here's where my question comes in: is there an accepted pattern for how to do this type of thing?  Thus far, I've just been deleting all the originally-pulled rows and then reinserting the newly-saved rows.  However, as each row has an auto-incremented ID, I'm starting to get worried (you can see how a single user could easily blow through 100,000 IDs in no time at all).  At some point in the future, I may also have foreign keys which depend on these rows IDs and of course this method will wreak havoc on them.

On the other hand, modifying each individual changed row--including keeping track of deletions and additions--seems like a recipe for mistakes.


问:
Are there any strong reasons to use DI for sub-classes that are known to be tightly coupled to their parent containers?
I have Product classes for Products A through Z.  And each Product class has its own set of product-specific subclasses, which I'd say are tightly coupled to them, like so:

//specific product class inherits from generic product
class ProductA extends Product
{
    function __construct()
    {
        parent::__construct();

        //product-specific subclasses that are tightly coupled to the product
        //note that they are not DI-ed, although they *could be*
        $this->weight = new WeightA();
        $this->spec = new SpecA();
    }
}

class Product
{
    public $weight;
    public $spec;

    function __construct()
    {
        //these are generic versions in case someone calls a generic product class
        $this->weight = new Weight();
        $this->spec = new Spec();
    }
}

//example instantiation
$p = new ProductA();
$p->weight->a_specific = 4;
```

<p><strong>Question:</strong></p>

<p>I spent a bit of time reflecting on whether I wanted to pass my <code>Weight</code> and <code>Spec</code> subclasses using Dependency-Injection techniques, like so (adjusting my classes respectively):</p>

```$p = new ProductA(new WeightA(), new SpecA());
```

<p>But so far I have found no good reason to do so.  In fact, doing so may increase the chance of error where I can by accident do something like this:  </p>

```$p = new ProductA(new WeightB(), new SpecC()); //note the disparate classes
```

<p>Question:  </p>

<ul>
<li>Are there any good reason to DI tightly-coupled subclasses into generic class containers anyway?</li>
<li>is there a common name for this issue (pattern) that I am dealing with?</li>
<li>are there other (better) patterns available to use in my instance?</li>
</ul>

<p><strong>Background:</strong></p>

<p>I am refactoring a large ball-of-mud application and it is getting some shape, but one of the patterns I have identified is that there are product-specific classes that contain a lot of product-specific sub-classes, such as in the above example.</p>

<p><strong>Possible Middle-Ground:</strong></p>

<p>Note:  alternatively if I really want to DI, I can use DI inside product-specific subclasses, injecting subclasses into the parent container (opposed to injecting it from the outside into the product-specific classes themselves like I have done above), like so:</p>

```class ProductA extends Product
{
    function __construct()
    {
        parent::__construct(new WeightA(), new SpecA());
    }
}

class Product
{
    function __construct($weight, $spec)
    {
        $this->weight = $weight;
        $this->spec = $spec;
    }
}
```

I wonder if that will be a better option overall.  One problem with it is that ProductA() has no parameters but Product($weight, $spec) will have two parameters, which is an inconsistency.

答:
Why is the tight coupling an issue? If I create a class containing two integer fields or properties, it is tightly coupled to the implementation of integers. Is this a problem? Only if you need to change the integer to a different type, selecting that type at run time.

The premise behind the question (tight coupling is a problem) seems flawed. We can always add more DI and more abstractions. But does it add anything from the user's viewpoint? Does it improve readability and reduce complexity? If you are adding things that are not needed, the answer is always no.


问:
Is serialization strategy part of an abi?
According to semver, the major version of a component must be updated when an abi-breaking change is incorporated. Wikipedia does a good job of describing how abi defines the interaction between different components and includes data types in its definition. But, I'm unsure whether that definition includes serializable objects (abstractly, not Java's horrible interface).

If the serialization strategy is not included in the definition, and a change is made to said strategy between minor versions, then I can imagine the following scenarios happening:

Machine running v1.0 makes a remote call to machine running v1.1 and the call fails.

Server with large persistent work queue updates from v1.0 to v1.1 and queue can no longer be processed.

Additionally, if the modification to the format can be made in a backwards compatible way, does that change anything?

答:
Serialized data is, well, data. If you break support for input files that used to work, or change the output files in ways that break external programs, that's a backwards incompatible change. If previously working input files are still supported and the changes to output files is such that it won't break external programs (or there are no external programs), it's a backwards compatible change. This holds for any files and data formats, regardless of whether "serialization" figures into their creation.

As with many API changes and bug fixes, this is a bit tricky: Almost anything has the potential to break some use case, however obscure, even if it technically doesn't affect the documented API. Serialization formats are usually undocumented, but (for good reasons!) generally the expectation is that serialized data from older versions can be read, unless explicitly and prominently documented otherwise. Violating this expectation will be considered a backwards incompatible change and no amount of hairsplitting will save you from the wrath of your users.

If the serialization format is documented (even if only as "it's a pickle file"), the case is even more clear cut. You documented that the file is in that format; changing the format in a way that breaks previously-compliant readers is backwards incompatible. Note that one can change a file format without breaking readers, as long as the change is not too radical and the original format was designed with extension in mind.


问:
Understanding basics of object declaration in Java
Is there a case when an object is declared without a call to the constructor?
as in, for example:

```<code>ArrayList<Integer> grades;
</code>```

Or is it always the case that  ArrayList<Integer> grades (as in our example here) would always be followed by a call to a constructor as in,

```<code>ArrayList<Integer> grades = new ArrayList<Integer>();
</code>```

?

If the latter is the case i.e. a declaration of an object is always followed by its initialization with a constructor then why isn't

```<code>ArrayList<Integer> grades;
</code>```

already implies

```<code>ArrayList<Integer> grades = new ArrayList<Integer>();
</code>```

Otherwise when is it the case that an object is declared without an immediate call to the constructor following it?

Is it the case that

```<code>ArrayList<Integer> grades;
</code>```

can be initialized by anything other than

```<code>= new ArrayList<Integer>();
</code>```

答:
Consider two distinct concepts: objects and references.

References 'point' to objects in memory, but they are not the objects themselves. In Java, we always refer to and control objects through references to them. In Java, you never store the object itself in the variable, only it's address in memory (not exactly - implementation dependent - but you get the idea).

So by declaring ArrayList<Integer> grades;, what you do is create a reference, which is able to point to objects of type ArrayList<Integer> (and any subtype).

And by declaring new ArrayList<Integer>(), what you do is create a new object in memory, and have a 'pointer' to it returned to you (not the actual object data).

So by declaring ArrayList<Integer> grades = new ArrayList<Integer>();, you create an ArrayList<Integer> somewhere in memory, and assign its memory address (again, sort of) to the variable grades.

Declaring only ArrayList<Integer> grades; creates an empty reference that points nowhere.


答:
Yes, references to objects can be initialized without constructors or visible assignments. This effect is often achieved by using Dependency Injection containers like Guice or Spring.

```<code>class Foo {
  @Inject
  Integer bar;
};

Foo foo = container.create(Foo.class);
assert foo.bar != null;
</code>```

If this class is instantiated in Injection container context, its field bar will get a value without ever being directly assigned. These usually use reflection to set values, so while assignment is not explicit it still happens.
I don't think we can do same trick for local variables.

Title: Understanding basics of object declaration in Java

Body:
Is there a case when an object is declared without a call to the constructor?
as in, for example:

```<code>ArrayList<Integer> grades;
</code>```

Or is it always the case that  ArrayList<Integer> grades (as in our example here) would always be followed by a call to a constructor as in,

```<code>ArrayList<Integer> grades = new ArrayList<Integer>();
</code>```

?

If the latter is the case i.e. a declaration of an object is always followed by its initialization with a constructor then why isn't

```<code>ArrayList<Integer> grades;
</code>```

already implies

```<code>ArrayList<Integer> grades = new ArrayList<Integer>();
</code>```

Otherwise when is it the case that an object is declared without an immediate call to the constructor following it?

Is it the case that

```<code>ArrayList<Integer> grades;
</code>```

can be initialized by anything other than

```<code>= new ArrayList<Integer>();
</code>```

Body:
Yes, references to objects can be initialized without constructors or visible assignments. This effect is often achieved by using Dependency Injection containers like Guice or Spring.

class Foo {
  @Inject
  Integer bar;
};

Foo foo = container.create(Foo.class);
assert foo.bar != null;

If this class is instantiated in Injection container context, its field bar will get a value without ever being directly assigned. These usually use reflection to set values, so while assignment is not explicit it still happens.
I don't think we can do same trick for local variables.