答:
In my experience, there are three ways to prevent the problems you described above:

Limit the scope of your variables

Name your variables something meaningful and descriptive

Use a pre-compiler to notify of any errors (Doval mentioned pylint for Python)

1) Limiting the scope of your variables will limit the first error.  You will have fewer variables that have the possibility of containing the same name.  Odds are that you won't have any collisions.  You can limit scope by declaring variables only in the scope that they will be used.  The reason this works is because variables will be disposed of as a result of the natural cycle in your code.  I've provided an example below for clarify.

```<code>class:
    classVariable = "classVar";

    function ThisIsAFunction(functionVar) {
        var functionVar2 = "functionVar2";
        if functionVar > functionVar2 :
            var ifStatementVar = "ifStatementVar";

            for i in range(0,2):
                ifStatementVar += i;
            // i will go out of scope here
        // ifStatementVar will go out of scope here
    // functionVar and functionVar2 will go out of scope here
</code>```

2) Naming your variables something meaningful will go a long way to preventing re-use of the same variable name.  The key in naming your variables is to make them specific enough that their name cannot be reused.  When refactoring code it is a good idea to look for function, variable and class names that can be renamed to better reflect their purpose and meaning.  An example of good variable names is the following:

```<code>function GetSumOfTwoIntegers(intFirstNum, intSecondNum):
    return intFirstNum + intSecondNum;
</code>```

There is a lot of discrepency when deciding on good names.  Everyone has their own style.  The main thing to ensure is that you it is clear to yourself and others what the method, parameter or class is supposed to do and be used for.  GetSumOfTwoIntegers as a method name tells anyone calling this method that they need to pass in two integers and they will be receiving the sum as a result.

3) Finally, you can use a pre-compiler to tell you of any mistakes that have been made.  If you are using a good IDE, it will notify you of any errors.  Visual Studio uses Intellisence to let the developer know of any errors before compiling.  Most languages have an IDE that supports this functionality.  Using one would certainly solve your second problem.

The reason someone might choose to create the syntax of a language in a specific way is hard to determine.  I can posture that in Python's case it was likely that the creator wanted to type less when writing code.  It only takes a print statement to create a Hello World program in Python.  Creating a comparable program in Java requires a lot more typing.  Anyways, I don't really know why the creator chose this syntax.

Title: Declaring variables in Python and PHP

Body:
The question is how to cope with absence of variable declaration in Python, PHP, and the like.

In most languages there is a way to let the compiler know whether I introduce a new variable or refer to an existing one: my in Perl (use strict) or \newcommand vs. \revewcommand in LaTeX. This prevents from two major sources of errors and headache:

(1) accidentally using the same name of a variable for two different purposes, such as in (PHP)

```<code>$v = $square * $height;
<...lots of code...>
foreach ($options as $k => $v)
    echo "For key $k the value is $v\n";
<...lots of code...>
echo "The volume is $v";
</code>```

or a lot nastier (PHP)

```<code>$a = [1, 2, 3];
foreach ($a as $k => &$v)
    $v++;
foreach ($a as $k => $v)
    echo "$k => $v\n";
</code>```

(can you see a bug here? try it!); and

(2) prevent from typos (PHP):

```<code>$option = 1;
$numberofelements = 1;
if ($option)
{
    $numberofelenents = 2;
}
echo $numberofelements;
</code>```

(can you see a bug here? PHP will execute silently).

Using something like my (Perl)

```<code>use strict;
my $option = 1;
my $numberofelements = 1;
if ($option)
{
    $numberofelenents = 2;
}
say $numberofelements;
</code>```

(Perl will immediately report the bug) is a tiny effort and HUGE benefit both in debug time and (much more importantly) in losses (potentially huge) from incorrect programs.

However, some languages, notably Python, PHP, and JavaScript, do not give any protection from these types of bugs.

My question is how can we effectively cope with this?

The only way I can foresee is to create two functions (PHP):

```<code>function a ($x)
{
    if (isset ($x))
        die();
    else
        return &$x;
}
</code>```

and

```<code>function the ($x)
{
    if (isset ($x))
        return &$x;
    else
        die();
}
</code>```

and use them always:

```<code>a($numberofelements) = 1;
the($numberofelenents)++;
say the($numberofelements);
</code>```

but of course this is extremely cumbersome. Any better way of effectively protecting from such errors?

No, "use another language", "be careful and don't make errors", and "split your code in tiny functions" are not good answers (the latter may protect from the errors of type 1 but not type 2).

Body:
In my experience, there are three ways to prevent the problems you described above:

Limit the scope of your variables

Name your variables something meaningful and descriptive

Use a pre-compiler to notify of any errors (Doval mentioned pylint for Python)

1) Limiting the scope of your variables will limit the first error.  You will have fewer variables that have the possibility of containing the same name.  Odds are that you won't have any collisions.  You can limit scope by declaring variables only in the scope that they will be used.  The reason this works is because variables will be disposed of as a result of the natural cycle in your code.  I've provided an example below for clarify.

class:
    classVariable = "classVar";

    function ThisIsAFunction(functionVar) {
        var functionVar2 = "functionVar2";
        if functionVar > functionVar2 :
            var ifStatementVar = "ifStatementVar";

            for i in range(0,2):
                ifStatementVar += i;
            // i will go out of scope here
        // ifStatementVar will go out of scope here
    // functionVar and functionVar2 will go out of scope here

2) Naming your variables something meaningful will go a long way to preventing re-use of the same variable name.  The key in naming your variables is to make them specific enough that their name cannot be reused.  When refactoring code it is a good idea to look for function, variable and class names that can be renamed to better reflect their purpose and meaning.  An example of good variable names is the following:

function GetSumOfTwoIntegers(intFirstNum, intSecondNum):
    return intFirstNum + intSecondNum;

There is a lot of discrepency when deciding on good names.  Everyone has their own style.  The main thing to ensure is that you it is clear to yourself and others what the method, parameter or class is supposed to do and be used for.  GetSumOfTwoIntegers as a method name tells anyone calling this method that they need to pass in two integers and they will be receiving the sum as a result.

3) Finally, you can use a pre-compiler to tell you of any mistakes that have been made.  If you are using a good IDE, it will notify you of any errors.  Visual Studio uses Intellisence to let the developer know of any errors before compiling.  Most languages have an IDE that supports this functionality.  Using one would certainly solve your second problem.

The reason someone might choose to create the syntax of a language in a specific way is hard to determine.  I can posture that in Python's case it was likely that the creator wanted to type less when writing code.  It only takes a print statement to create a Hello World program in Python.  Creating a comparable program in Java requires a lot more typing.  Anyways, I don't really know why the creator chose this syntax.


问:
Security Concerns with password storage in Scripting Languages (VBA)
The team I work with handles large amounts of consumer survey, and internal company metric data. Primarily the data is stored in a database, and we utilize various platforms and to work with that data, including MS Excel.

My peer has developed a suite of Excel/VBA files to take the raw data we get and upload it into a database. Unfortunately, after a code review we identified that the database password was displayed in the VBA code, in plain text, in several places per file. Being in a large enterprise organization we had a number of concerns about those files being available to more than just our team, and the database password being compromised.

The problem is, I feel the solution is just as bad, if not worse than the original problem. The plaintext passwords have been removed in the code of all of the VBA files, and an ancillary, helper file was created that requires the user to authenticate through our organizations LDAP system before gaining access to the database password. Being a scripting language (and being Excel), I feel there really aren't adequate precautions in place to secure the users password in the helper file. I feel that now instead of compromising access to a single database, we are potentially compromising access to the logins of anyone who uses these files.

To be fair, my peer has implemented a number of security minded techniques for securing the data in helper file. I just feel each one can easily be circumvented:

locking the VBA code [google search for vba password recovery]

using a custom "masked" password entry box [the password box may be masked, but it is still passed out of the box as plaintext]

not actually storing the user password in the file itself (he passes it on directly to the LDAP call) [a break point or stop statement can easily reveal the contents of what was passed]

setting the sheets to VeryHidden to prevent direct access [append .zip to filename, and ALL data in ALL worksheets is accessible]

As I'm not one to complain without a solution in mind, our organization already employs Active Directory/LDAP for authentication into our individual machines. My thought is that checking the logged in user (not a full user/password, just the user) against a white list of users on the database should be a sufficient alternative for authentication.

So My Question...

Am I being too paranoid about this? Is there another, more appropriate solution? I am pushing back fairly hard on this fix and I just wanted a sanity check before I start to involve others in yet another solution.

答:
One possibility would be to use INTEGRATED SECURITY=sspi in your connection string, like this you don't have to specify user/password and access would be handled through Active Directory login and DB permissions (you'd need to setup DB access for allowed users for this to work).

I also found this other article on Stack Overflow where they explain how to create an external DLL that can be used to retrieve the connection object obscuring all details in that compiled library.

ContentLicense: CC BY-SA 3.0


问:
Changing story-point estimates after closing the story
In a running multi-year multi-team project there is a set of stories that have been fully estimated and closed, having fulfilled the definition of done. Time has progressed and possibilities in Jira Agile have advanced, making it more useful to group user stories using an Epic to describe the total goal of the set of stories. There are new stories groomed and estimated that belong to these same epics, however the comparison between the old story points and the new story points cannot be made to fit: the new story points are worth less per story point.

Is it acceptable to re-estimate the completed stories, increasing the number of story points  that were completed a year ago? What sort of problems may arise from this if the changes are handled as scope changes?

答: It sounds like you've changed the definition, value, sensitivity of a story point (time, complexity, etc), so you're really doing a conversion and not a re-estimation. Unless there is more to it, it's no different then changing from entering in days and then changing to hours. Just do the math but it's really worth the same based on today's definition.</p>


问:
How to write JavaScript while keeping HTML/CSS out of it
What is / are some recommended ways to write JavaScript as to control behavior of showing HTML on screen, while keeping well-maintainable code?  Basically, I started to look for ways to keep HTML/CSS out of JS (assuming it's the recommended practice), but I might as well check into the latest ways of writing JavaScript well.  See below for more details.

My specific problem

I have JS files that look something like this:

var selection = eval("(" + document.getElementById("result").innerHTML + ")");

if (selection[index].selected) {
    result += '
';
    result += '
';
    result += 'Data	';
    result += '
';

    var flag = "All";

    if (selection[index].flag == 'P')
        flag = "Premium";

    result += '
';
    result += 'Flag	';
    result += '' + flag + '	';
    result += '
';
    result += '
';
}

document.getElementById('final').innerHTML = result;
```

In fact, entire JS codebase I work with is plagued by this.  You can see here HTML, CSS JS, and JSON (selection var gets its content from JSON prepared by PHP earlier).  I want to make this better.

My experience level

I am new to writing good JS or to having experience with JS patterns, tools, tips, techniques, and so on.  I am looking for help with those.

My specific issue:

I have a series of tables and data to be shown to the user.  It is a "series", so user can select which "element" of the series is currently active on the screen.  An "element" is essentially an HTML partial (with JS and CSS and HTML), and is described below:

"element":  a block of HTML that serves as static data (tables, titles, and divs), and a long JSON string that encodes some previously prepared data.  JSON string is assigned to a JS variable and that JSON data/JS variable stores records numbered 1 through n, where each i holds various data to be injected into the block of HTML, forming "HTML partial".

I have navigational buttons on the screen, allowing user to step through the "series", where the HTML is the same, but the data inside it changes.

I am looking for a good way to write this "step through HTML blocks" functionality using what is considered to be good maintainable JS code.  Namely, I am looking for the following characteristics:

separation of concern

cleaner code - I need tools or techniques to allow me to avoid mixing HTML with JS with CSS (as in seen my example), unless where necessary or convenient.  (what I have now is not convenient)

I prefer techniques rather than tools, but open to considering/evaluating well-established tools.  By "techniques", I mean pure JS, HTML, CSS, PHP approaches.  By "tools", I currently know and trust jQuery, and for other tools prefer to have some track record to them.

Note on HTML visibility/hiding

I should also perhaps note that in my case HTML is static, aka it does not change structurally, as I step through the elements.  However, based on the JSON/selection variable, some blocks of HTML are show/hidden (as is shown in my example).  Once they are shown/hidden at page render time, they stay shown/hidden throughout stepping through selection.

答:
My initial thoughts

extract HTML from JS, and place HTML in HTML file (same with CSS)

load JS in parent container's HTML file

in JS file use JS/jQuery to show/hide DIVs in HTML as needed as per selection var

use JS/jQuery to bind navigational events to buttons

have navigational events populate table cells via assigned id attributes.

A bit of a pain to rewrite what I have now, but hopefully the end result will be more maintainable and easier to extend / customize.  i.e. for HTML I can go to HTML and edit that and use HTML tools for things there, rather than dealing with HTML embedded as strings in JavaScript.  Same with CSS.  I am still not sure if that effort will be entirely worth it, as things do work as they are now... except that it's a long mess of a JS file.


问:
Google is good or bad for programmer?
Recently I was being interviewed by a company and faced one question. The interviewer asked me a question and at that time I didn't know the answer but if I had been asked about just 4 months ago, I could have answered it.

The question was from new language that I learned just 4 months ago. But I just get overview of the language and just get started working on that. Whenever I face difficultly, I google it. That means we do not have to memorize the whole programming language book! So in that situation I felt that Google screwed my job!

Not talking subjectively, Is it good to google all the time?

答:
Having Google - or rather the web and a search engine - is a lot better than not having it.

However in response to "Is it good to google all the time?" I don't think so - but then again I'm relatively ancient in Computing terms (graduated in '82) and perhaps my google-fu is not the greatest.

I'm particularly unhappy with the notion that:

Google however is great as a replacement for paper books, manuals, everything really

because it isn't (well not unless we renamed "the web" to "google" whilst I was asleep).

It is certainly true that there is a great deal of information on the web and that a great deal of that is either a copy of or a replacement for paper books, manuals etc. It is also true that google (or bing), can be (though is not always) an excellent means to find content on the web. Problem is that there is also a lot on the web that is dated (or refers to the wrong version) or is just plain wrong and, in the case of many of the questions I ask, a lot of asking and very little answering (and those questions and less than helpful discussion threads are echoed all over the place by sites that think it helpful - or profitable - to endlessly duplicate other sites).

I think there are two keys for me:

You should start with the manual - or, since those often don't exist any more, the specific help for the tools your using (local or remote). This usually covers the basics. Only when that fails do you reach for your search engine (and even then you might - probably should - have specific sites to visit first - or target to search first). Of course the manuals don't have all the answers - but for the more "interesting" questions finding a good answer on the web can be a challenge

One still needs to read books - they give you depth and insight and show you things you won't find hunting issue specific answers. Even turning the pages of a manual or browsing the VS2010 help web pages when trying to find an answer will put things in front of you that you might not otherwise have seen (and would likely dismiss as not being relevant in a web search).

To be clear - I'm not against using google to find information on the web - I do so all the time - its the notion that its the first place one starts that worries me.

ContentLicense: CC BY-SA 2.5

Title: Google is good or bad for programmer?


问:
Declaring variables in Python and PHP
The question is how to cope with absence of variable declaration in Python, PHP, and the like.

In most languages there is a way to let the compiler know whether I introduce a new variable or refer to an existing one: my in Perl (use strict) or \newcommand vs. \revewcommand in LaTeX. This prevents from two major sources of errors and headache:

(1) accidentally using the same name of a variable for two different purposes, such as in (PHP)

```<code>$v = $square * $height;
<...lots of code...>
foreach ($options as $k => $v)
    echo "For key $k the value is $v\n";
<...lots of code...>
echo "The volume is $v";
</code>```

or a lot nastier (PHP)

```<code>$a = [1, 2, 3];
foreach ($a as $k => &$v)
    $v++;
foreach ($a as $k => $v)
    echo "$k => $v\n";
</code>```

(can you see a bug here? try it!); and

(2) prevent from typos (PHP):

```<code>$option = 1;
$numberofelements = 1;
if ($option)
{
    $numberofelenents = 2;
}
echo $numberofelements;
</code>```

(can you see a bug here? PHP will execute silently).

Using something like my (Perl)

```<code>use strict;
my $option = 1;
my $numberofelements = 1;
if ($option)
{
    $numberofelenents = 2;
}
say $numberofelements;
</code>```

(Perl will immediately report the bug) is a tiny effort and HUGE benefit both in debug time and (much more importantly) in losses (potentially huge) from incorrect programs.

However, some languages, notably Python, PHP, and JavaScript, do not give any protection from these types of bugs.

My question is how can we effectively cope with this?

The only way I can foresee is to create two functions (PHP):

```<code>function a ($x)
{
    if (isset ($x))
        die();
    else
        return &$x;
}
</code>```

and

```<code>function the ($x)
{
    if (isset ($x))
        return &$x;
    else
        die();
}
</code>```

and use them always:

```<code>a($numberofelements) = 1;
the($numberofelenents)++;
say the($numberofelements);
</code>```

but of course this is extremely cumbersome. Any better way of effectively protecting from such errors?

No, "use another language", "be careful and don't make errors", and "split your code in tiny functions" are not good answers (the latter may protect from the errors of type 1 but not type 2).

答: In addition to the analysis tools, your IDE can also help you suss out these types of issues. I made the move to PyCharm because it handles these types of things much more effectively, than say, Eclipse & PyDev. It is a much more visual IDE that helps you prevent these issues. </p>

Title: Declaring variables in Python and PHP


问:
What is a good design approach in .NET for performing a series of checks in background process?
I have a flight planning system in .NET/SQL Server which needs to perform several validation checks. This needs to work on both a windows and a web client. Currently the checks run synchronously but this is slowing the system down, plus it is often repeating the same checks. Like "is this aircraft in the right start location", "is the aircraft available" and many more complicated checks. This is needed since the current system does not know if other flights have been changed which might cause issues.

Am looking for a way in which I could create a single background process which runs independently and asynchronously on an interval and might be triggered by data changes or explicit requests. This process could then update a list of found issues per flight. Another process could simply use this list to report the issues to the user without having to perform the checks itself.

Any ideas on architecture pattern and best practices to implement something like this?
Would like to keep the installation process fairly simple, so the fewer "moving parts" the better.

答:
One method that I used in a somewhat similar position that allowed me to force integrity on the data while ensuring a speedy experience for my users was to asynchronously build the request on the server side.

So, if feature A (.75 seconds to process calculations), B (2 seconds), and C (3 seconds) were all part of a single page and when I posted this page the processing time for A + B + C was just too great. 5.75 seconds isn't horrible, but people start noticing speed at this point. My page processing actually took about 10 seconds because of everything that needed to be done. To fix this I split them into separate functions on the same page.

When you added A (let's say aircraft position that does 20 different calculations on things and took .75 seconds), it was asynchronous. I had a server side function that did the processing for this, including checks, file movement, etc. The information for A was stored on the server as part of a partial request (I used REDIS to keep this information).

When you add your B information, the processing again happens asyncronously.

And C.

So, when you finally hit "Submit", you don't have to do all that processing again. It's been already done and the results / information / verification are on the server waiting as a partial submission. Your actual submission would kick of a process that basically says "take the partial information on the server and combine it into x (x being a record, request, or whatever you finally do with it)".

I realize I'm being high-level. I can try to provide a code sample if you want. But, my 10 seconds synchronous process of a page (ain't nobody have time for that), turned into multiple submissions for the page. People don't mind waiting 1 second after they update each part of the page. When they actually post the page, all the work has been done in the background, so the response time is about 1 second. They think it's really quick, but it's only because all the work was already done.

One note, the purpose for storing the information on the server side helps prevent security issues. If you only "check" A when they complete it on the page and send back an, "It's all good," message, but then on submission, take the value of A from the submission information assuming it's the same information that you checked, you could open yourself up to malicious data. I receive the partial information, store it server side, and on post, use that information so I know with 100% certainty that the information I'm using is what has already passed all my checks.

Hope that helps!


问:
Passing data between hundreds of objects in java
Currently, I'm working with a group on building a model. This model simulates interactions between many "agents" in a region. Agents can be any entity such as a city, a farmer, a business etc. Each agent is represented by its own object within java. Each agent will need to be able to interact with all of the other agents, and therefore, needs to have access to information about the other agents.

So, for example, lets say we have 1 city object interacting with 99 farmer objects. The city needs to know for instance, the total land that each of the 99 farmers owns in order to perform some sort of calculations.

So, my question is, what is the most performance efficient way of completing something like this? There may even be 500-1000 or more agents in the future, and each agent may need to access many variables from the other agents. Would you potentially set up a table within mysql for each agent and have them access eachother's information that way?
Or can something be set up directly within java that allows the agents to access each other's information.

I'm looking to possibly multithread this model in the future too. In any case, I want the most performance efficient way of completing this.

答:
You have two options:

Every agent knows about every other agent, and queries those agents as needed.

Every agent publishes its state changes, and other agents listen to the changes they care about.

The second approach has several benefits over the first, most important being that changes only happen when necessary. For example, if only 2 farmers trade land, the city doesn't need to query the other 97 farmers.

There are many ways to go about implementing this. I would not put a database in the mix, but would instead use an in-memory event bus with publishes and subscribers. There are ready-made systems to do this, or you could roll your own.


答:
Use a mvw (model/view/whatever) pattern

model: "pure" javascript library modelling abstract concepts. This part usually contains objects & methods names related to the application domain (car business -> car objects / insurance contracts) and the data access logic.

view: a custom language describing how your UI look like. Preferably, the language should be close to HTML.

something to make both part communicate without having one depend too much on the other. A change in the model data must result in a change in the corresponding elements of the view (model -> view). A mouse click mouse result in a method call somewhere in the model (view -> model).

With those concepts, you can choose different stacks

You can use a big framework such as angular. The views are html dom template. The model is divided between controllers & services.

you can use backbone (~model) + jquery (~view)

you can use react.js

... the list goes on. The number of tools available is actually pretty scary. Check http://todomvc.com/ for a nice list of examples.

Example solution with angular

In angular, the connection between the model & the view is performed with a viewmodel & dual way data binding. A view model is a javascript object. Both the view & the model can read & write to this object, and react to changes.

in your view, you write the HTML:

```<code><TABLE class="list_grey" style="float: left; margin-left: 20px;" ng-hide="hideAll">
<TR ng-repeat="row in rows">
    <td ng-repeat="val in row" ng-class="{selected : val.sel}"> {{ val.label }} </td>
</TR>
</TABLE>
</code>```

in your controller, you only deal with javascript values:

```<code>$scope.rows = [
    [{label : "foo"}, {label : "bar"}],
    [{label : "foo2"}, {label : "bar2", sel : true}]
]

$scope.hideAll = false;
</code>```

ng-repeat allows you to display a list of items. ng-class & ng-hide are used to control the class & visibility of the elements.

Closing words

Using other frameworks, the resulting organization may vary, but the essential separation still exists. In react.js, the data binding is unidirectional, which implies different construct. The mvw framework usually deals with the communication between the components, so you don't have to use jquery at all.

This is a good thing if your project isn't trivial. Managing a complex app with only jquery can lead to a mess of callback interactions which may become hard to maintain.

Using a full mvw framework such as angular or ember requires some learning. Some other libraries have a smaller scope such as react.js & knockout.js.

Of course you don't have to start learning one of these tools right now. The important thing is to achieve the separation between the view & the model. You can use jquery to write functions which will edit the dom according to observation made on a pure javascript library.

You can also use jquery to write the (view -> model) callbacks. (model -> view) can be written using publisher/observer. This part should be as small as possible, and be the only thing connecting the model and the views.

Title: How to write JavaScript while keeping HTML/CSS out of it

Body:
What is / are some recommended ways to write JavaScript as to control behavior of showing HTML on screen, while keeping well-maintainable code?  Basically, I started to look for ways to keep HTML/CSS out of JS (assuming it's the recommended practice), but I might as well check into the latest ways of writing JavaScript well.  See below for more details.

My specific problem

I have JS files that look something like this:

var selection = eval("(" + document.getElementById("result").innerHTML + ")");

if (selection[index].selected) {
    result += '
';
    result += '
';
    result += 'Data	';
    result += '
';

    var flag = "All";

    if (selection[index].flag == 'P')
        flag = "Premium";

    result += '
';
    result += 'Flag	';
    result += '' + flag + '	';
    result += '
';
    result += '
';
}

document.getElementById('final').innerHTML = result;
```

In fact, entire JS codebase I work with is plagued by this.  You can see here HTML, CSS JS, and JSON (selection var gets its content from JSON prepared by PHP earlier).  I want to make this better.

My experience level

I am new to writing good JS or to having experience with JS patterns, tools, tips, techniques, and so on.  I am looking for help with those.

My specific issue:

I have a series of tables and data to be shown to the user.  It is a "series", so user can select which "element" of the series is currently active on the screen.  An "element" is essentially an HTML partial (with JS and CSS and HTML), and is described below:

"element":  a block of HTML that serves as static data (tables, titles, and divs), and a long JSON string that encodes some previously prepared data.  JSON string is assigned to a JS variable and that JSON data/JS variable stores records numbered 1 through n, where each i holds various data to be injected into the block of HTML, forming "HTML partial".

I have navigational buttons on the screen, allowing user to step through the "series", where the HTML is the same, but the data inside it changes.

I am looking for a good way to write this "step through HTML blocks" functionality using what is considered to be good maintainable JS code.  Namely, I am looking for the following characteristics:

separation of concern

cleaner code - I need tools or techniques to allow me to avoid mixing HTML with JS with CSS (as in seen my example), unless where necessary or convenient.  (what I have now is not convenient)

I prefer techniques rather than tools, but open to considering/evaluating well-established tools.  By "techniques", I mean pure JS, HTML, CSS, PHP approaches.  By "tools", I currently know and trust jQuery, and for other tools prefer to have some track record to them.

Note on HTML visibility/hiding

I should also perhaps note that in my case HTML is static, aka it does not change structurally, as I step through the elements.  However, based on the JSON/selection variable, some blocks of HTML are show/hidden (as is shown in my example).  Once they are shown/hidden at page render time, they stay shown/hidden throughout stepping through selection.

Body:
Use a mvw (model/view/whatever) pattern

model: "pure" javascript library modelling abstract concepts. This part usually contains objects & methods names related to the application domain (car business -> car objects / insurance contracts) and the data access logic.

view: a custom language describing how your UI look like. Preferably, the language should be close to HTML.

something to make both part communicate without having one depend too much on the other. A change in the model data must result in a change in the corresponding elements of the view (model -> view). A mouse click mouse result in a method call somewhere in the model (view -> model).

With those concepts, you can choose different stacks

You can use a big framework such as angular. The views are html dom template. The model is divided between controllers & services.

you can use backbone (~model) + jquery (~view)

you can use react.js

... the list goes on. The number of tools available is actually pretty scary. Check http://todomvc.com/ for a nice list of examples.

Example solution with angular

In angular, the connection between the model & the view is performed with a viewmodel & dual way data binding. A view model is a javascript object. Both the view & the model can read & write to this object, and react to changes.

in your view, you write the HTML:

<TABLE class="list_grey" style="float: left; margin-left: 20px;" ng-hide="hideAll">
<TR ng-repeat="row in rows">
    <td ng-repeat="val in row" ng-class="{selected : val.sel}"> {{ val.label }} </td>
</TR>
</TABLE>

in your controller, you only deal with javascript values:

$scope.rows = [
    [{label : "foo"}, {label : "bar"}],
    [{label : "foo2"}, {label : "bar2", sel : true}]
]

$scope.hideAll = false;

ng-repeat allows you to display a list of items. ng-class & ng-hide are used to control the class & visibility of the elements.

Closing words

Using other frameworks, the resulting organization may vary, but the essential separation still exists. In react.js, the data binding is unidirectional, which implies different construct. The mvw framework usually deals with the communication between the components, so you don't have to use jquery at all.

This is a good thing if your project isn't trivial. Managing a complex app with only jquery can lead to a mess of callback interactions which may become hard to maintain.

Using a full mvw framework such as angular or ember requires some learning. Some other libraries have a smaller scope such as react.js & knockout.js.

Of course you don't have to start learning one of these tools right now. The important thing is to achieve the separation between the view & the model. You can use jquery to write functions which will edit the dom according to observation made on a pure javascript library.

You can also use jquery to write the (view -> model) callbacks. (model -> view) can be written using publisher/observer. This part should be as small as possible, and be the only thing connecting the model and the views.


问:
How useful are infix operators in a programming language?
How useful are infix operators in a programming language? Are they worth the extra complexity they provide? Can you provide any examples where infix operators are better suited to the problem that can't be handled by just overloading the normal operators?</p>

答:
I think infix operators stem from mathematics.

This:

```<code>2 + 3 * 4
</code>```

is more readable to most people, than

```<code>(+ 2 (* 3 4))
</code>```

because most people are familiar with mathematics.

Interesting enough in Haskell you can hop between infix and prefix.
This is using the same funtion "(+)":

```<code>(+) 1 2
1 + 2
</code>```

and this is using the same function "elem":

```<code>elem 42 [1,2,42]
42 `elem` [1,2,42]
</code>```

Body:
I think infix operators stem from mathematics.

This:

2 + 3 * 4

is more readable to most people, than

(+ 2 (* 3 4))

because most people are familiar with mathematics.

Interesting enough in Haskell you can hop between infix and prefix.
This is using the same funtion "(+)":

(+) 1 2
1 + 2

and this is using the same function "elem":

elem 42 [1,2,42]
42 `elem` [1,2,42]


答:
Depending on which browsers you need to support, you may be able to take advantage of the HTML 5 template tag.

The template tag allows you to keep your partial HTML elements in the HTML file but not have them rendered in the browser. In order to actually display the contents, you clone the template's contents and add it to the DOM using javascript. You can clone and add as often as needed during runtime, while only defining and maintaining the contents of the HTML once, keeping things nice and DRY.

Keeping your CSS and JS in separate files is also a very good practice, so that you can perform minification to improve how fast your page downloads. It also allows your css and js to be re-used across multiple pages in your site and cached by the browser between those requests, again improving the site's performance. It also allows you to use different tools for the different file types, or use a web development IDE that has different syntax highlighting and other language-specific features based on the language of the file.

HTML 5 rocks has a good tutorial on the template tag with sample code.

Putting it Together

extract the HTML in your JS and place it into a template tag in your main html file

place css in its own file

place JS in its own file

include the css and js files in your html file

in your js file, create separate functions to clone the template tag's contents, add your JSON data into the appropriate part of the cloned contents, add the contents to the DOM.

in your js file, create a function to call the above functions appropriately based on the selection var

bind your navigational events to the nav buttons

Caveats

Since this is a new tag, it only works in a few browsers (currently Firefox and Chrome). If your site needs to work in other browsers, you will want to use a polyfill which is alternate javascript and html code that handles the cases where the browser support is not there yet.


问:
Should an abstract class always abstract its methods to an interface?
I had learned sometime ago that abstract classes should always abstract their functions to an interface. So instead of having something like this -

```<code>abstract class a{
    public int i;
    public int foo();
}

class b : a{
    public int foo(){return 42;}
}
</code>```

we have something like this -

```<code>interface Ia{
    public int foo();
}

abstract class a : Ia{
    public int i;
}

class b : a{
    public int foo(){return 42;}
}
</code>```

From my perspective, this is better because of single responsibility, modularity, and maintainability. My colleague disagrees though, and states that there is no perceivable advantage to this and that it only adds to complexity. I tried to find some writing on this topic, but I cant remember the pattern name and my googling hasn't turned anything up.

Is this pattern an actual thing? Was I right to abstract everything as much as I can, or is my colleague correct?

答:
Neither. Abstract classes and interfaces are not substitutable. If your class has a binary operation (that is, it inspects the private fields of another instance of its class), this simply can't be done from an interface (because an interface hides its implementation). This is why, for example, you don't see a union/merge operation in Java's Set interface.

However, if you do need multiple implementations of a type then using interfaces is definitely the better approach when applicable. You can't multiply-inherit classes, so as soon as you need something that has both foo and bar, you're sunk. You can always implement multiple interfaces and reuse behavior with composition.


答:
You both can be correct. In general, your approach falls under the purview of the Interface Segregation Principle and his falls under You Ain't Going to Need It.

In my experience, it depends on what the interface is. Does it represent a concrete thing, or does it represent a trait of a variety of things?

If it represents a concrete thing, then just leave it as the abstract class. Making it an interface tempts people to multiply implement it, violating the Single Responsibility Principle since you're then mixing your concrete thing and some other thing.

If it represents a trait that is held by a variety of things, then make it an interface. The interface better models the trait and lets a variety of things satisfy the interface.

Don't make interfaces because you're "supposed to". Make interfaces because they properly model your problem domain.

Title: Should an abstract class always abstract its methods to an interface?

Body:
I had learned sometime ago that abstract classes should always abstract their functions to an interface. So instead of having something like this -

```<code>abstract class a{
    public int i;
    public int foo();
}

class b : a{
    public int foo(){return 42;}
}
</code>```

we have something like this -

```<code>interface Ia{
    public int foo();
}

abstract class a : Ia{
    public int i;
}

class b : a{
    public int foo(){return 42;}
}
</code>```

From my perspective, this is better because of single responsibility, modularity, and maintainability. My colleague disagrees though, and states that there is no perceivable advantage to this and that it only adds to complexity. I tried to find some writing on this topic, but I cant remember the pattern name and my googling hasn't turned anything up.

Is this pattern an actual thing? Was I right to abstract everything as much as I can, or is my colleague correct?


问:
Trying to understand how MySQL license applies to code I wrote
I have an ERP, coded with Java and the database in MYSQL Community edition. When I was going to sell it to a client he asked me for the sources to my application (with the belief that it is GPLed). I already got an upfront payment from him.  But now he asks me to deliver the source code for my ERP with the executable.

When I told him no, he responds that as I am using MySQL community edition the project must be open source, and I must give him the sources. He is not willing pay extra for the source for what I wrote.

It doesn't seem like the MySQL license should affect the license of the code I have written.  But is that true?

答:
The GPL does not require that you GPL license any software that connects to MySQL (When are you required to have a commercial MySQL license?).

If you just have your database sitting there, and connect to it, and could swap out the MySQL database for MariaDB, or PostgreSQL, or Oracle, or what have you your application is not a derived work of MySQL and does not need to be GPLed.

If, on the other hand, you have embedded MySQL within your application as a single bundle (see MySQL as an Embedded Database and Guide to MySQL as an Embedded Database), it does become a derivative work and your options are either to buy a commercial license for MySQL (one license choice) or be constrained by the GPL.

The above is specifically in context of connecting to a database.  It says nothing about the libraries or means of connecting to that database.  Note that the ConnectorJ library is under the GPL.  Linking to that library would make the application fall under the GPL too.  There are other connectors which may or may not have a different license that does not entail that linking application is GPL.  However, just connecting to a database that is under the GPL does not mean your application is under the GPL too.

As always, I am not a lawyer.  If you need a lawyer, you should get one.  If this becomes an issue of contract resolution, you likely need a lawyer.

Consider also contacting MySQL directly and asking for their answer that you could then relay to your client.


问:
Why does C# allow properties in interfaces?
In C#, the following code is valid

```<code>interface I{
    int property{get;set;}
}
</code>```

Which doesn't make any sense to me. This seems to break one of the most important principles of interfaces: lack of state (in other words, no fields). Doesn't the property create an implicit private field? Wouldn't that be really bad for interfaces?

答:
Defining the property as you've shown is the same as defining methods int GetProperty() and void SetProperty(int i). Properties are powerful short-hand in C#.

A property does not implicitly create a private field in C#. That is the default implementation of an auto-property, for example public string MyString { get; set;} - however, a property which defines custom logic in the get method does not generate an implicit private field.

Lastly, as interfaces are concerned with public API, what would it matter if the implementation of an interface property relied on a private field - implicit or otherwise? That is hidden from consumers of the interface regardless.


答: Properties are methods! A backing field will be added to the class which implements the interface (either manually or through an auto-property).

Title: Why does C# allow properties in interfaces?

Body:
In C#, the following code is valid

```<code>interface I{
    int property{get;set;}
}
</code>```

Which doesn't make any sense to me. This seems to break one of the most important principles of interfaces: lack of state (in other words, no fields). Doesn't the property create an implicit private field? Wouldn't that be really bad for interfaces?


问:
Observing progress of a distributed system
For a distributed system, there is a requirement of observing the progress of
smaller applications on distributed computers (runtime 5 - 20 minutes).

There is a web fronted, which right now only shows a list of those smaller
applications (called jobs), with the state of each of
them, like preparing, running, finished

So in web-ui, an administrator can see:

name

state

starting time

call parameters

from any computer in the network, possibly for the whole system.

Each of the properties is stored in the database, so each state change leads
to a call to write to the database. There might be thousends of those jobs
at a time.

Description of the distributed system:

Central components, served at one location only:

Database server (holding results of the jobs to runs statistics, have an overview of jobs run the last three month etc)

Application server (glassfish, java, runs central server software)

Distributed components, each site has at least one, connected via internet / WAN area:
(probably about 20 sites, each has 1..4 Job controllers, each job controller runs about 20 jobs in parallel)

Job-controller component (windows, c#, wcf, starts and observes small jobs)

Small applications running tasks, started by Job-Controller (the jobs)

So, for a vague estimation:

```<code>20 sites * 4 Job-controllers * 20 jobs = 1600 jobs in parallel

each of which runs from 0 to 100 percent in about 5 minutes on average,
resulting in a progress update each 3 seconds.

giving 533 progress updates per second (over the internet)
</code>```

Now the customer wants to see something like a progressbar for each of these
jobs.

At first, I thought this might lead to a high network traffic and to a vast amount of traffic on the database server.

I do not think that writing progress like 1%, 2%, 3% to the database is a good idea.
The runtime of those jobs is not very easy to be estimated good (so it is near enough
to a real result), but each job can tell very well what his progress is.

What would be a good architectural approach to observe progress of possibly thousends of those mini-jobs? (Please note that a mixed infrastructure is given. There is the constraint that the system will be built upon that. so: Central glassfish + java and per site Windows + WCF + C#)

Right now I think that each Job-controller could update the progress of all jobs it controls every 10 seconds at once. Would that be an acceptable approach?

答:
This looks like a dashboard. There are a number of dashboard platforms out there that can be configured as to data sources, polling intervals, etc.

Let me suggest a rough design, while challenging some of your assumptions.

Assumption: You state that there is a central database that holds the results of each job. I don't see a requirement that it holds the status of each job while it is running.

Assumption: Detailed progress, at the % level, is not required. It is sufficient to show progress (or lack of progress, with a red flag).

Assumption: 1400 jobs, updating at 15 second intervals each (which is about 5% increments), is 5600 updates per minute, or 93 updates per second.

Assumption: The user interface component can extrapolate the speed of progress from recent updates and provide any smoothing of the dashboard animations.

For your architecture, consider using a distributed messaging framework such as Akka.NET. Each job reports its information and progress to an actor on its host machine. Host machines (I presume there is more than one host machine per site) report progress to a site machine, which forwards the job report to the central server. You may decide to update the database with progress, or not, as you see fit.

On the central server, the web server collects and summarizes the job information. For each job, you have the job identification, start time and parameters, most recent progress reported and progress rate, along with the time stamp. This summary is forwarded to the web page itself (via AJAX queries), where the UI takes each job and displays the progress bar and periodically updates it based on progress and progress rate.

This general approach to the web page design allows you to throttle progress updates as you tune the application, perhaps allowing the web page to focus on one or a few sites at a time for frequent updates. It also off-loads progress bar updates to the client where any kind of animation may be displayed.

Similarly, the use of the Akka.NET framework provides robust, fault tolerant distributed, reactive communication and updates. It will allow you to identify sites or hosts becoming unreachable, which should likely be displayed on the dashboard.


问:
Is it a bad idea to use mutable for pre-allocated temporaries?
Let us assume I have the following C++ class:

```<code>class MyFastMessageEncoder
{
public:
    MyFastMessageEncoder() :
        m_fieldEncoder(ENCODING_STYLE_DEFAULT)
    {
    }

    void set_encoding_style(const EncodingStyle encodingStyle)
    {
        m_fieldEncoder.set_encoding_style(encodingStyle);
    }

    EncodingStyle get_encoding_style() const
    {
        return m_fieldEncoder.get_encoding_style();
    }

    void encode(const UnencodedFieldList &unencodedFieldList, Message &message
    {
        for (UnencodedFieldList::const_iterator it = unencodedFieldList.begin(), end = unencodedFieldList.end(); it != end; ++it)
        {
            m_fieldEncoder.set_raw_data(*it);
            message.add_field(m_fieldEncoder.encode());
        }
    }

private:
    FieldEncoder    m_fieldEncoder;
};
</code>```

The MyFastMessageEncoder class is required to be extremely efficient (encoding will be performed on tens of thousands of messages per second), the time required to instantiate the FieldEncoder object is a non-negligible cost, so to solve the issue, I have defined the FieldEncoder object as a class member, and initialized it inside the constructor just once.

My issue is that FieldEncoder::SetRawData() is a non-const method, which means that the MyFastMessageEncoder::encode method must also be non-const. However, if I were to make the FieldEncoder object a temporary inside the method, MyFastMessageEncoder::encode could be flagged as const. This means that every object that calls  MyFastMessageEncoder::encode is also non-const, which (to me) just starts ruining the program's const-correctness.

Now I understand how the mutable keyword works works, and how I could use it to solve this problem, but my question is: Would doing so be considered bad form, since the internals of the object are technically being modified?

Other considerations:

Thread-safety is not a concern, this is guaranteed to only run in a single thread (although the MyFastMessageEncoder may be created on multiple threads)

The set_raw_data method does not impact the FieldEncoder class outside the MyFastMessageEncoder::encode method. Any data that is set is cleared or overwritten the next time the set_raw_data method is called.

答:
If encoding depends on previous fields, then MyFastMessageEncoder::encode is obviously non-const as it changes the observable state of the instance - calling it twice won't give the same result, therefore the state of the instance has changed, therefore it should be non-const.

Otherwise it seems a bit odd that you have, in the FieldEncoder, both a costly initialisation and that the state following set_raw_data is governed only by the data that's set. This suggests to me that the initialisation cost might be reduced - either sharing some of whatever structures are set up, or by pooling encoders.

However, both of those refactorings would be much more involved than making the encoder mutable, so if the initialisation cost is not causing problems elsewhere I would comment that the encoder only exists as a member as an optimisation for encode and make it mutable.


答:
In addition to the points that @MichealT made ...

If what you were doing was (hypothetically) a breach of the GPL, the License is actually between you and the MySQL copyright holders (i.e. Oracle).  Your customer has no right under law to demand that the license terms be enforced.  It would be up him to persuade Oracle to do that.  That means that Oracle's position on whether you are breaching the GPL is doubly pertinent.

Based on the facts as described, you may or may not be breaching the GPL.  It boils down to whether you are embedding MySQL in your product, or simply connecting to it.

And there's another way you could remedy this.  Buy a commercial license from Oracle to allow you to embed MySQL.  Then the GPL terms no longer apply.

(I am not a lawyer either ...)

Title: Trying to understand how MySQL license applies to code I wrote

Body:
I have an ERP, coded with Java and the database in MYSQL Community edition. When I was going to sell it to a client he asked me for the sources to my application (with the belief that it is GPLed). I already got an upfront payment from him.  But now he asks me to deliver the source code for my ERP with the executable.

When I told him no, he responds that as I am using MySQL community edition the project must be open source, and I must give him the sources. He is not willing pay extra for the source for what I wrote.

It doesn't seem like the MySQL license should affect the license of the code I have written.  But is that true?


问:
Whats the best way to build a HTML/AJAX site that requires login?
Let's say that hypothetically you wanted to build a website that delivered content to the visitors entirely using HTML and Javascript (AJAX to fetch server side data). The site would require login for certain functions. Let's also say, for the sake of discussion, you have the ability to create necessary web service methods that would be called from AJAX (for authenticating a user, getting data from a database, etc).

What would be the best way to implement this site? Would there be any advantages / drawbacks compared to building a site using a server side language like ASP.NET or PHP?

EDIT 1

First, thanks to everyone that has replied so far. I didn't properly phrase my question so I'm getting responses that aren't addressing my question. I've built many sites using traditional methods - a database backend and a frontend that was a mix of server side languages (.NET or PHP) and client side scripting JavaScript / jQuery.

Let's say I'm going to build an environment that has a database server, a web services server, and a web server. My web services server has all the methods I need to interact with the database (authentication, CRUD operations, reporting, etc). The web server does not support any server side languages (like PHP or ASP.NET).

I know it would be possible to build the site entirely in HTML, CSS, and JavaScript (jQuery). A user could be authenticated via AJAX, the authentication token could be stored in a cookie, and then token could be used on all subsequent AJAX requests.

My questions are:

What would be the advantages / drawbacks of such an approach?

What challenges would be faced with authentication and security?

Would this solve any of the problems typically faced when building a website?

If your boss was asking you to use this environment, would you argue against it? Why or why not?

答:
Login using AJAX, jQuery and PHP: https://stackoverflow.com/questions/14449118/php-ajax-login

Personally I think PHP is barbaric. The only acceptable use is if you're using a framework like CakePHP or Laravel. My preference is Django Python or Node.js. But there is no disadvantage to which backend you use. Each language has its strengths and can perform whatever you need to.

The main advantage of having a framework is that they can usually handle authentication for you. You shouldn't handle authentication yourself because chances are that you will have security vunerabilities in the way you do it.


问:
Technical reasons to prefer coding business logic to support Unicode (when not required)
I have a legacy application in which the UI and business logic are already reasonably well-separated. There is a proposal to separate them even further, turning the core application into a "service" (without UI) and writing a kind of "UI Server" as part of it to which various UIs (potentially in various languages, and for various different devices and operators) can connect to get/set the data to drive the application via those UIs.

On the surface, this seems to make a nice separation between the business logic, which is currently completely ignorant of the possibility of Unicode, and the UI, which is going to need to get very familiar with Unicode to support multiple languages in the UI(s).

Now this application essentially monitors a production process, and has very little (if any) traffic directly from UI to database via the business layer. It strikes me that the "natural language" of this process might as well be Chemistry or Mathematics, and so internally I should stick to the language that best describes it, so long as I can translate from that language into anything any UI requires (which I believe should be possible). This leads me to prefer (the simplicity and familiarity and least work path of) retaining old-fashioned 8-bit chars over moving to Unicode.

Are there any technical reasons to reject keeping the business logic part of an application ignorant of Unicode like this? And even if the "natural language" of the system were "English-without-too-many-strings-or-dates" rather than Chemistry, would that make a difference?

答:
I'm not sure I like this answer, and even though it's my own, I'm not going to prefer it. But I can't rule out in my own mind that it is a good thing to do in some situations, so I'll offer it.

If you've seen the movie "Gravity", you'll have seen Sandra Bullock's character trying to control a spacecraft whose controls are labelled in Russian. But those controls could equally be labelled with numbers. Now it would be entirely possible to write the kind of user manual used in the film in any language at all, referring only to the numbers of the controls. Indeed, those control labels could all be small displays which display a number until a language is identified, at which point they could display language-appropriate labels.

So here's the whole point of the example: no matter how you change the labels, the spacecraft is still going to fly the same. (Also, it helps that it's a non "English-centric" example to ground this in).

My question (and this answer) stem from recognising that there are certain applications for situations like this (such as production process control and monitoring) where the essential application (or the spaceship in this example) doesn't conform strongly to the normal "database/business logic/UI" model of doing things. Instead, maybe a "state machine/business and-or process logic/UI/database" model of things makes more sense.

That is to say, we all aim for the "holy grail" of separation between UI and business logic... but then we hamper ourselves in that effort by storing elements in the database that are not essential to the business logic in the slightest. But where else would we store them if there is only one database, and it is only accessed via the business logic?

So maybe there is a case to be made (in certain applications that suit it) for keeping the business logic independent of the database that supports the UI, and the UI independent of the database (or state machine) that supports the business logic.

This would allow the business logic to be written in a more natural language (which may be FORTRAN, PLC ladder diagrams, LISP, "Chemistry", etc, and which may be a terrible language to write a UI in) while writing a UI for multiple languages and/or devices in something which is suited to that purpose.

As I say, I'm not sure I like this solution, but I can see situations where it is well worth consideration.


问:
Object Design & Cohesion - Issue & potential refactoring
Abstract

I have been trying to get my head around the cohesiveness of some functionality in our code base.  I’ve approached this design in different ways, and lately I’m convinced that I took the wrong approach, as in I incorrectly applied the Single Responsibility Principle.

Issue

The problem domain is a Well, otherwise known as a round hole in the ground.  The current code looks something like this...  I have a set of data in a data only object...

Note: This is not the full code, just method names to keep things short...

```<code>public class WellData
{
    public string Name { get; set; }
    public ICollection<SurveyPoint> SurveyPoints { get; set; }
    public ICollection<GeometryItem> GeometryItems { get; set; }
    public ICollection<TemperaturePoint> WellTemperature { get; set; }
    public ICollection<FluidPoint> WellFluids { get; set; }
}
</code>```

I broke functionality that operates on this data into several small classes. As per below…

```<code>public class ReferenceWellSurvey
{
   ICollection<SurveyPointCalculate> _calculatedSurveyPoints;
   double GetTvdAtDepth(double depth) {}
   double GetAzimuthAtDepthRad(double depth) {}
   double GetInclinationAtDepthRad(double depth){}
   double GetTortuosityPeriodAtDepth(double  depth ) {}
   double GetTortuosityAmplitudeAtDepth(double depth ) {}
}

public class ReferenceWellGeometry
{
   ICollection<GeometryItem> _geometryItems;
   double GetFrictionAtDepth(double depth) {}
   double GetHoleIdAtDepth(double depth) {}
}

public class ReferenceWellTemperature
{
   ICollection<TemperaturePoint> _wellTemperatures;
   double GetTemperatureAtDepth(double depth) {}
   double GetSurfaceTemperature(double depth) {}
}
Etc.
</code>```

I’ve realized lately when looking at our code that I have to glue all this back together to make it usable where I need it in the application logic.  Something like….

```<code>public class ReferenceWellData
{
private IReferenceWellGeometry _refWellGeometry;
private IReferenceWellTemperature _refWellGeometry;
          private IReferenceWell _refWellGeometry;
          private IReferenceFluid _refWellFluid;
       //Proxy functions from each class to glue it all back together…
}
</code>```

A few things that led me to the current mess. The well data class contains several collections of information and if everything is in one class most functions will only operate on a small subset of the data.  At the time I felt that would create low cohesion, now a few months later, I feel these things do actually all belong together.  Additionally, there are several classes in my code that need to call just one method of the ReferenceWellSurvey class, GetTvdAtDepth().  Really what I did didn’t solve this issue.

After thinking more about this, and after reading this Wikipedia article http://en.wikipedia.org/wiki/Cohesion_(computer_science), I’m starting to see that I have committed a few programming sins.

•   Anemic domain model

•   Low cohesion

•   Constructor over injection in code where I try to glue things together

•   Giving a class that depends on GetTvdAtDepth access to other methods that it does not need, violated Interface Segregation Principle.

Solution

I’m looking for that Goldilox design that doesn’t give too much responsibility to any one class (No God Objects), while yet maintaining a good degree of cohesion.

My current thoughts on fixing this are as follows.  Move the functionality that operates on the well data into the same class.  This should help get this functionality closer to Communicational/informational cohesion.

```<code>public class WellData : IWellData
{
    public string Name { get; set; }
    public ICollection<SurveyPoint> SurveyPoints { get; set; }
    public ICollection<GeometryItem> GeometryItems { get; set; }
    public ICollection<TemperaturePoint> WellTemperature { get; set; }
    public ICollection<FluidPoint> WellFluids { get; set; }

   // Operates on SurveyPoint collection
   double GetTvdAtDepth(double depth) {}
   double GetAzimuthAtDepthRad(double depth) {}
   double GetInclinationAtDepthRad(double depth){}
   double GetTortuosityPeriodAtDepth(double  depth ) {}
   double GetTortuosityAmplitudeAtDepth(double depth ) {}
   //Operates on WellGeometry collection
   double GetFrictionAtDepth(double depth) {}
   double GetHoleIdAtDepth(double depth) {}
   //Operates on WellTemperature collection
   double GetTemperatureAtDepth(double depth) {}
   double GetSurfaceTemperature(double depth) {}
}
</code>```

Next to address the issue of several classes needing just one function, I could make this one function into a separate interface IGetTvdAtDepth.  In this way, my classes that need that functionality can depend just on this interface, which I can inherit into my WellData interface, and implement it there, but not tie my other classes to all the functionality that is in my WellData class.

Thoughts on this approach vs. the original approach?  One thing that bothers me about doing things way is that in my API I'm using bastard injection to fulfill the required dependencies of this class... Right now I have three required dependencies, a Survey calculator, and a special class that references data at different measured depths. I'd like to move away from this, but that seems to point back toward having services do more of the lifting...

答:
Note

Any answer will be biased by the description of the problem/model we were given; there may be other ways of looking at the domain that are more helpful

Caveats aside

It looks like you have a Well class and several collections of related Measurements on a well. If the measurements may be repeated at different times, then any single Well may have several sets of Measurements, even of the same kind

this leads to a simple structure: an object and a set of measurements/calculations on the object -

```<code>Well - a concrete class for an instance of a well, including properties intrinsic to the well (like HoleID or Name)
WellOperation - an abstract class for a set of related Measurements on a specific Well
    ReferenceWellTemperature - a bunch of temperature measurements
    ReferenceWellGeometry - a bunch of geometry measurements
    etc.

</code>```

Each operational subclass contains data in reference to a particular well. A single well may have zero or more of these, possibly multiples of the same kind taken at different points in time

So you do not need - and do not want - an overarching class like the ReferenceWellData example; the number and kinds of measurement operations may change, which will cause the overarching class' interface to change, and that's not necessary

Body:
Note

Any answer will be biased by the description of the problem/model we were given; there may be other ways of looking at the domain that are more helpful

Caveats aside

It looks like you have a Well class and several collections of related Measurements on a well. If the measurements may be repeated at different times, then any single Well may have several sets of Measurements, even of the same kind

this leads to a simple structure: an object and a set of measurements/calculations on the object -

Well - a concrete class for an instance of a well, including properties intrinsic to the well (like HoleID or Name)
WellOperation - an abstract class for a set of related Measurements on a specific Well
    ReferenceWellTemperature - a bunch of temperature measurements
    ReferenceWellGeometry - a bunch of geometry measurements
    etc.

Each operational subclass contains data in reference to a particular well. A single well may have zero or more of these, possibly multiples of the same kind taken at different points in time

So you do not need - and do not want - an overarching class like the ReferenceWellData example; the number and kinds of measurement operations may change, which will cause the overarching class' interface to change, and that's not necessary


问:
Algorithm to reverse engineer permutation
I have a sequence of permutations formed using these strings: "A", "BC" and "D". The permutations are:

```<code>BCAD
ABCD
BCDA
DABC
ADBC
DBCA
</code>```

Now I need to reverse engineer this; i.e. I have a text file containing the sequences, I should be able to tell the strings that are used to construct the permutations. What algorithm I can use?

答:
This is related to the Longest common substring problem and can be solved using a Generalized suffix tree.

Use Ukkonen's algorithm to Build a tree (not a binary tree), adding nodes as you parse the file. Ukkonen's algorithm works in O(n) (linear) time, for constant-size alphabets, and O(n log n) in general.

The leaf nodes of the tree can then be traversed to obtain the original sequences.


问:
What term is used to describe running frequent batch jobs to emulate near real time
Suppose users of application A want to see the data updated by application B as frequently as possible.  Unfortunately app A or app B cannot use message queues, and they cannot share a database. So app B writes a file, and a batch job periodically checks to see if the file is there, and if load loads it into app A.

Is there a name for this concept?  A very explicit and geeky description:
"running very frequent batch jobs in a tight loop to emulate near real time".

This concept is similar to "polling".  However polling has the connotation of being very frequent, multiple times per second, whereas the most often you would run a batch job would be every few minutes.

A related question -- what is the tightest loop that is reasonable.  Is it 1 minute of 5 minutes or ...? Recall that the batch jobs are started by a batch job scheduler (e.g. Autosys, Control M, CA ESP, Spring Batch etc.) and so running a job too frequently would causes overhead and clutter.

答:
When I was working at a bank,
the guys in architecture claimed "we have the only real-time banking system in Australia, all the others use fast-batch" *.

Which was exactly as you describe,
they would run a batch processing of all pending transactions several thousand times a second.

So fast-batch is a term that is in use to do what you describe.

*The truth of their claims is not relevant to this question


问:
What are the boundaries of Domain Events?
As I get it, domain events imply loose coupling and separation of responsibilities. That's fine. But if domain events are allowed to cross aggregate's boundaries then it is a question how to guarantee that all concerned entities are materialized from persistence storage? For now it looks like events can only bubble through aggregate to the root or be handled by services triggering in-transaction scripts. In the letter case I believe the targeting specifics of the event is lost.

Again and again My questions arise from the fact that the whole model does not live in the memory.

答:
Normally the component that listens for domain events is an adapter ('adapter' as in the "ports & adapters" architecture design) or perhaps a domain service. This components are usually stateless and are instantiated in the start of the application.

In the book Implementing DDD by Vaughn Vernon there is one chapter dedicated to domains events. I cannot reproduce here because its a complex concept, but the book has code examples (in java) and will probably solve a lot of your doubts about Domain Events.

I recommend reading Vernon's whole book if you are really interested in DDD; IMHO its the best book on the subject, with realistic examples and real approaches to implement the ideas in the original Eric Evans Book.


答:
Get the data design done first.  Understanding what data you need for each entity, and how the entities relate should simplify your design.

You may find you have many entities which can be modeled as sub-types.  Different sub-types may have different behavior, but should contain the same state (data).  Understanding the common and specific behaviors of similar agents will help you design your class hierarchy.

You will likely want a database for persistence, but keep the behavior in the application.  I would expect most of the data to be at rest (persisted to the database) most of the time.  Databases can be quite efficient at answering questions like how many acres do the farmers in this city have.

If by agent you mean objects, then you are looking at a rather small set of data.  You may be able to keep the data in an in-memory database.  Even if you don't the data may well fit in the database and/or operating system memory.

EDIT:  The container should be pooling connections to the database so you shouldn't have any agents connecting to the mysql.  They should be asking model object (database proxies) for data, and those may run a database query.  Well designed databases are very efficient at gathering data about related entities (agents).

Unless you are running simulations of long term data, it is unlikely the changes will happen often enough to make an observer/mediator type structure work very well.  This pattern more appropriate when data is changing several times a minute, not several times a year.  Even with hundreds of farmers, I would expect changes to be minutes between during harvest season, and days between the rest of the year.

If you are doing everything in memory you risk loosing all the data whenever the application goes down.  Over a period of years, this will be a certainty.  Being able to update and restart the application would appear to be essential to your design evolution.

Title: Passing data between hundreds of objects in java

Body:
Currently, I'm working with a group on building a model. This model simulates interactions between many "agents" in a region. Agents can be any entity such as a city, a farmer, a business etc. Each agent is represented by its own object within java. Each agent will need to be able to interact with all of the other agents, and therefore, needs to have access to information about the other agents.

So, for example, lets say we have 1 city object interacting with 99 farmer objects. The city needs to know for instance, the total land that each of the 99 farmers owns in order to perform some sort of calculations.

So, my question is, what is the most performance efficient way of completing something like this? There may even be 500-1000 or more agents in the future, and each agent may need to access many variables from the other agents. Would you potentially set up a table within mysql for each agent and have them access eachother's information that way?
Or can something be set up directly within java that allows the agents to access each other's information.

I'm looking to possibly multithread this model in the future too. In any case, I want the most performance efficient way of completing this.


答:
You cannot use HTML and AJAX on its own to access your databases or data stored on remote/hosting server.  You will need a server side scripting language PHP, ASP, PERL, CGI, etc.

HTML and AJAX run on the "client side", the computer accessing the web page.  The server side languages run on the "server".  HTML can invoike AJAX to access a server side script which in turn will return a value and said value can be parsed and pushed back to web page.

PHP is the most popular and simplest of them all so it may be a good start.  I use PHP and have found that combined with JQuery, there is simply nothing I cannot do.

Title: Whats the best way to build a HTML/AJAX site that requires login?

Body:
Let's say that hypothetically you wanted to build a website that delivered content to the visitors entirely using HTML and Javascript (AJAX to fetch server side data). The site would require login for certain functions. Let's also say, for the sake of discussion, you have the ability to create necessary web service methods that would be called from AJAX (for authenticating a user, getting data from a database, etc).

What would be the best way to implement this site? Would there be any advantages / drawbacks compared to building a site using a server side language like ASP.NET or PHP?

EDIT 1

First, thanks to everyone that has replied so far. I didn't properly phrase my question so I'm getting responses that aren't addressing my question. I've built many sites using traditional methods - a database backend and a frontend that was a mix of server side languages (.NET or PHP) and client side scripting JavaScript / jQuery.

Let's say I'm going to build an environment that has a database server, a web services server, and a web server. My web services server has all the methods I need to interact with the database (authentication, CRUD operations, reporting, etc). The web server does not support any server side languages (like PHP or ASP.NET).

I know it would be possible to build the site entirely in HTML, CSS, and JavaScript (jQuery). A user could be authenticated via AJAX, the authentication token could be stored in a cookie, and then token could be used on all subsequent AJAX requests.

My questions are:

What would be the advantages / drawbacks of such an approach?

What challenges would be faced with authentication and security?

Would this solve any of the problems typically faced when building a website?

If your boss was asking you to use this environment, would you argue against it? Why or why not?


问:
Android SDK and Iphone SDK limitations
I have an idea that would require triggering a call or text message simply by pressing or dialing a certain number.

Example: Pressing 2324 on the pin code. Despite it not being your pin code to unlock the device, my application (always running in the back) would detect your code "2324" has been typed in and send a call or text message.

Another Example: Holding volume button for 5 seconds and then pressing "2" on pin code lock. This could be another trigger.

My question is, how flexible are the iOS and Android SDK's to allow this level of customization? Can I override tone settings via an application (change from Silent to Normal)? Can I close applications? What can't I do?

I tried researching this but have not come up with any recent or updated answer. Hoping someone could clarify what I can't/can do with Iphone and Android SDK's.

答:
I'm an iOS developer so I don't know much about Android, but the way that iOS works is that each app is inside its own "sandbox" so that the apps cannot call actions on each other such as closing. This is done as a security measure. More on App Sandboxing (paragraph 'The App Sandbox').

The only way apps can interact is through urls such as "tel:1-408-555-5555" to open the phone app and pre-enter the phone number 1-408-555-5555. More on device urls here. You can custom configure urls for your app, for example Facebook and Twitter have their own app urls you can call from your app to open up Facebook or Twitter if the user presses a certain button or whatnot. But after that, all control of the device and the user interaction is up to Facebook or Twitter, not your app. If they are posting a status and the Facebook app closes after that, then control is returned to your app, but there is only one dominant and active app at a time.

As far as volume, I'm not 100% sure but I don't think you can control silent/sound since that is controlled by a hardware switch on the side of the device.

Overall, no, Apple doesn't let you interfere with other apps. If you have an app running in the background, it cannot pick up on activity done within another app (due to the sandbox).

So I dug through the Android docs a bit and found this article on interacting with other apps. Most interestingly is this subarticle which seems to indicate that you can collect a result from another app. This might be what you're looking for? However I don't know how you would collect results form the lock keypad as that's not really an "app", more of just the OS itself.
It seems that this use is more of like opening contacts and getting the info for which contact the user selected, which iOS supports that functionality too. But there's no like "listening in" on just any app. Again, not an Android guy.

Title: Android SDK and Iphone SDK limitations


问:
Approach to managing multiple services like Evernote, Google drive, dropbox in iOS
I'm trying to think up a scenario when I'd have three different forms of NSData (or whatever) to be sent to three different services like Evernote, Google drive, Dropbox. Granted, each of those has there own SDKs to be bundled into the iOS app, and thats okay.

Now, I want to create a single Class that serialises the both sending and receiving data to and from the above services.

My mind is taking me to a singleton, a shared class with NSOperationQueue at its foundation.

I'd periodically add {send:"this data" to:dropbox} into an NSOperationBlock and add it to the singleton.

At any given time say the following operations could be within the singleton's NSOperationQueue.

{send:"this data"   to:dropbox}

{send:"this number" to:evernote}

{send:"this dude"   to:googledrive}

The singleton would need to handle internet reachability, app sessions etc. This class would be connected to Dropbox, Evernote and GDrive and their respective SDK bundles. So, in reality the only thing this class would do is, hand over the data to the respective SDKs to handle it on their own (which is like saying, handle it and let me know if it was a success or failed.)

I'd really like suggestions/critique on the approach i'm taking. I have little experience with NSOperationQueue, I don't know if I'm making the right choices here. Some clues to a good API pattern would really be helpful.

UPDATE

It was suggested I create a wrapper for each service. But If can stress that theres little to do in a Dropbox Wrapper classes, Since in iOS everything is handled in their own SDK. For example, Evernote extends only a simple [ENSession .. uploadNote..]. All I wanted to do, is serialise my uploads into a single global queue and then dispatch the single methods to either Dropbox or Evernote or wherever. If suppose there is a service that requires some form of data handling, I'd then use a wrapper and dispatch its own thread. I'll add this into the question too. Its the serialising & queueing I want.Sounds reasonable?

答:
Break the services into their own respective classes. Even if a class only has one function in it, it will add much better readability, and thus scalability and be readily editable in the future. Stick to the Unix philosophy that each class should do only one thing, and do that one thing well. So I would have one class handle internet reachability using the notification center and three classes for each service. For example, here is a singleton class I once used with Google Drive.

```<code>#import <Foundation/Foundation.h>

#import "GTLDrive.h"
#import "GTMOAuth2Authentication.h"
#import "VSGConstants.h"

@interface VSGGoogleServiceDrive : GTLServiceDrive

/**
 Static method for having a shared Google service across the app
 */
+ (VSGGoogleServiceDrive *)sharedService;

@end
</code>```

```<code>#import "VSGGoogleServiceDrive.h"

@implementation VSGGoogleServiceDrive

+ (VSGGoogleServiceDrive *)sharedService {

    static VSGGoogleServiceDrive *sharedServiceDrive = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedServiceDrive = [[VSGGoogleServiceDrive alloc] init];
    });
    return sharedServiceDrive;
}

- (id)init {

    self = [super init];
    if (!self){
        return nil;
    }
    GTMOAuth2Authentication *auth = [[GTMOAuth2Authentication alloc] init];
    auth.accessToken = GOOGLE_ACCESS_TOKEN;
    auth.refreshToken = GOOGLE_REFRESH_TOKEN;
    auth.tokenURL = [NSURL URLWithString:GOOGLE_TOKEN_URL];
    auth.clientID = GOOGLE_CLIENT_ID;
    auth.clientSecret = GOOGLE_CLIENT_SECRET;
    self.authorizer = auth;
    return self;
}

@end
</code>```

Extremely simple, but the individual service is nicely decoupled, making it more plug-n-play. This was from an old app so with my xp now, I would go ahead and also implement my service functions here such as uploading NSData to drive or deleting folders/files, etc.

I was also using the Google Calendar service, but kept that in it's own singleton as well.

Here's also my Reachability class using Tony Million's Reachability.

```<code>#import "Reachability.h"
#import "VSGConstants.h"

/**
 This class is used to monitor network connection. Dependent on the Reachability class. Provides an
 alert view to the user detailing the network connection upon network changes (disconnect/connect).
 */
@interface VSGNetworkMonitor : NSObject

/**
 Network used to check whether there is a valid connection to the server
 */
@property Reachability *network;

- (void)startMonitoringNetwork;

@end
</code>```

```<code>    #import "VSGNetworkMonitor.h"

@interface VSGNetworkMonitor()

- (void)checkNetworkStatus:(NSNotification *)notice;

@end

@implementation VSGNetworkMonitor

static NSString *CONNECTION_LOST_TITLE = @"Connection Lost";
static NSString *CONNECTION_LOST_MESSAGE = @"Unable to connect to the server. Please check your connection";

static NSString *NO_CONNECTION_TITLE = @"Network Issue";
static NSString *NO_CONNECTION_MESSAGE = @"No valid internet connection detected";

static NSString *CONNECTION_FOUND_TITLE = @"Connection Found";
static NSString *CONNECTION_FOUND_MESSAGE = @"Connection to the server restored";

- (id)init {

    self = [super init];

    if(!self) {

        return nil;
    }

    self.network = [Reachability reachabilityWithHostname:SERVER_IP];

    if([self.network currentReachabilityStatus] == NotReachable) {

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NO_CONNECTION_TITLE
                                                        message:NO_CONNECTION_MESSAGE
                                                       delegate:self
                                              cancelButtonTitle:OK_BUTTON
                                              otherButtonTitles:nil];
        [alert show];
    }

    return self;
}

- (void)startMonitoringNetwork {

    [self.network startNotifier];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(checkNetworkStatus:)
                                                 name:kReachabilityChangedNotification
                                               object:nil];
}

- (void)checkNetworkStatus:(NSNotification *)notice {

    NetworkStatus internetStatus = [self.network currentReachabilityStatus];
    switch (internetStatus) {

        case NotReachable: {

            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:CONNECTION_LOST_TITLE
                                                            message:CONNECTION_LOST_MESSAGE
                                                           delegate:nil
                                                  cancelButtonTitle:OK_BUTTON
                                                  otherButtonTitles:nil];
            [alert show];
            break;
        }

        case ReachableViaWiFi:
        case ReachableViaWWAN: {

            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:CONNECTION_FOUND_TITLE
                                                            message:CONNECTION_FOUND_MESSAGE
                                                           delegate:nil
                                                  cancelButtonTitle:OK_BUTTON
                                                  otherButtonTitles:nil];
            [alert show];
            break;
        }
    }
}

@end
</code>```

Don't avoid breaking things apart. Instead, to the contrary, break things apart as much as you can. This also helps with Information Hiding as well.

Body:
Break the services into their own respective classes. Even if a class only has one function in it, it will add much better readability, and thus scalability and be readily editable in the future. Stick to the Unix philosophy that each class should do only one thing, and do that one thing well. So I would have one class handle internet reachability using the notification center and three classes for each service. For example, here is a singleton class I once used with Google Drive.

#import <Foundation/Foundation.h>

#import "GTLDrive.h"
#import "GTMOAuth2Authentication.h"
#import "VSGConstants.h"

@interface VSGGoogleServiceDrive : GTLServiceDrive

/**
 Static method for having a shared Google service across the app
 */
+ (VSGGoogleServiceDrive *)sharedService;

@end

#import "VSGGoogleServiceDrive.h"

@implementation VSGGoogleServiceDrive

+ (VSGGoogleServiceDrive *)sharedService {

    static VSGGoogleServiceDrive *sharedServiceDrive = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedServiceDrive = [[VSGGoogleServiceDrive alloc] init];
    });
    return sharedServiceDrive;
}

- (id)init {

    self = [super init];
    if (!self){
        return nil;
    }
    GTMOAuth2Authentication *auth = [[GTMOAuth2Authentication alloc] init];
    auth.accessToken = GOOGLE_ACCESS_TOKEN;
    auth.refreshToken = GOOGLE_REFRESH_TOKEN;
    auth.tokenURL = [NSURL URLWithString:GOOGLE_TOKEN_URL];
    auth.clientID = GOOGLE_CLIENT_ID;
    auth.clientSecret = GOOGLE_CLIENT_SECRET;
    self.authorizer = auth;
    return self;
}

@end

Extremely simple, but the individual service is nicely decoupled, making it more plug-n-play. This was from an old app so with my xp now, I would go ahead and also implement my service functions here such as uploading NSData to drive or deleting folders/files, etc.

I was also using the Google Calendar service, but kept that in it's own singleton as well.

Here's also my Reachability class using Tony Million's Reachability.

#import "Reachability.h"
#import "VSGConstants.h"

/**
 This class is used to monitor network connection. Dependent on the Reachability class. Provides an
 alert view to the user detailing the network connection upon network changes (disconnect/connect).
 */
@interface VSGNetworkMonitor : NSObject

/**
 Network used to check whether there is a valid connection to the server
 */
@property Reachability *network;

- (void)startMonitoringNetwork;

@end

    #import "VSGNetworkMonitor.h"

@interface VSGNetworkMonitor()

- (void)checkNetworkStatus:(NSNotification *)notice;

@end

@implementation VSGNetworkMonitor

static NSString *CONNECTION_LOST_TITLE = @"Connection Lost";
static NSString *CONNECTION_LOST_MESSAGE = @"Unable to connect to the server. Please check your connection";

static NSString *NO_CONNECTION_TITLE = @"Network Issue";
static NSString *NO_CONNECTION_MESSAGE = @"No valid internet connection detected";

static NSString *CONNECTION_FOUND_TITLE = @"Connection Found";
static NSString *CONNECTION_FOUND_MESSAGE = @"Connection to the server restored";

- (id)init {

    self = [super init];

    if(!self) {

        return nil;
    }

    self.network = [Reachability reachabilityWithHostname:SERVER_IP];

    if([self.network currentReachabilityStatus] == NotReachable) {

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NO_CONNECTION_TITLE
                                                        message:NO_CONNECTION_MESSAGE
                                                       delegate:self
                                              cancelButtonTitle:OK_BUTTON
                                              otherButtonTitles:nil];
        [alert show];
    }

    return self;
}

- (void)startMonitoringNetwork {

    [self.network startNotifier];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(checkNetworkStatus:)
                                                 name:kReachabilityChangedNotification
                                               object:nil];
}

- (void)checkNetworkStatus:(NSNotification *)notice {

    NetworkStatus internetStatus = [self.network currentReachabilityStatus];
    switch (internetStatus) {

        case NotReachable: {

            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:CONNECTION_LOST_TITLE
                                                            message:CONNECTION_LOST_MESSAGE
                                                           delegate:nil
                                                  cancelButtonTitle:OK_BUTTON
                                                  otherButtonTitles:nil];
            [alert show];
            break;
        }

        case ReachableViaWiFi:
        case ReachableViaWWAN: {

            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:CONNECTION_FOUND_TITLE
                                                            message:CONNECTION_FOUND_MESSAGE
                                                           delegate:nil
                                                  cancelButtonTitle:OK_BUTTON
                                                  otherButtonTitles:nil];
            [alert show];
            break;
        }
    }
}

@end

Don't avoid breaking things apart. Instead, to the contrary, break things apart as much as you can. This also helps with Information Hiding as well.


问:
Multiple many to many relations or one option table?
Let's say I have a database of persons who have some properties. For the sake of this problem let's say all of these properties relate as N-N.

I can either create two tables for each property (one for different values and one for cross-referencing them to the main object).

Or, I can make the following structure:

Basically having just one huge table of values.

Are there any advantages to this approach? Also, does this approach or pattern have a name that I can look up?

UPDATE:
For example, we make classifier pets with properties cat, dog and fish. So one person may have a cat and a dog (or one pet, or none). And we make a classifier hobby with values skiing, skating, football and TV. So Joe has properties cat, dog, and TV. Then cat and dog are pets and TV is hobby.

The question is, is it worthwhile to put this data using this diagram, or is it a better idea to just create pets, pets_xref, hobby, hobby_xref tables?

答:
Unless you fully understand and accept the consequences, doing this is generally not advisable if it can be avoided.

People are often tempted to use this model. In theory you can create any database with just four tables: objects, properties, values, links. While this kind of generic data model is very flexible, it is also very inefficient to query, and any complex queries you have to write against it will be very ugly.

Basically, you are depriving yourself of many of the benefits the RDMS is designed to give you.

Here's a post which discusses it in more detail: https://asktom.oracle.com/pls/asktom/f?p=100:11:0::::p11_question_id:10678084117056


问:
Referencing StackOverflow questions in comments
Often when coding I'll get stuck on a particularly tricky problem and will go about searching for a solution. More often than not this leads me to a StackOverflow question that provides a full or partial solution, often with code than can be used directly by pasting into the original code.

In some cases this can lead to code that looks unintuitive or does some seemingly unusual things - such as overloading existing methods in classes, reimplementing in-built functions with the same name or otherwise breaking some aspect of "good practise" to achieve a solution. Sometimes these look like bad practise, but due to problems in the code

In cases like these I often find myself including a link to the answer that I've implemented, with some brief explanation rather than rewriting or duplicating verbose explanations.

Is including URLs to solutions for these kinds of problems in comments a common practise, or is there a better way to document this kind of code?

As an example of this kind of issue, I recently asked a question about resolving a conflict with the Python property decorator, where the solution was to rename the Python in-built function and included a link to the question in the code.

答:
I do this a lot. I will write comments linking to SO answers, linking to Github issues, linking to anything where more information about the specific problem/answer may be found.

There are caveats to doing so:

In the case of SO questions, the question might be deleted, or the answer might edited or deleted, and it may no longer be relevant;

Any other links may also have their content edited, or be removed altogether.