问:
Compare SSIS and MDS/DQS
How does Master Data Services and Data Quality Services fit into the existing BI stack?

In SSIS there is a Fuzzy Lookup and Fuzzy Grouping component.  Therefore I am tring to compare: SSIS v MDS/DQS.

From what I understand MDS/DQS is the preferred solution if you are processing records on a transaction by transaction basis e.g. end users updating individual records.  SSIS is the preferred solution if you are processing records as a batch i.e. batch processing.  Is that correct?

答:
All three of these tools have very different functionality.

SSIS is an ETL (i.e. Extract, Transform, Load) tool. Yes, it's for batch processing of data, and also for parallel processing of multiple data flows. In the case of BI, its main job is population of various data warehouse tables. Those might be staging tables, or they might be the actual warehouse tables. It can also be used in plenty of non-BI situations where data needs to be transformed and moved. The Fuzzy Lookup and Fuzzy Grouping components pre-date MDS and DQS, and are fairly limited, but potentially still useful in some scenarios or if there's no intention to adopt DQS.

MDS is a data integration tool. The intention is to use it in situations where an organisation has multiple transactional databases with overlapping data, and there's a need to pull that data together and integrate it. That means setting up rules to determine how to match the data from the different systems. It can also be used to push the centralized data back out to transactional systems to resolve cases where data was different in different systems. It's an attempt to get "one version of the truth" in either a centralized place, or across all systems.

DQS is a data quality tool. It provides functionality to allow developers and data stewards to work together on setting up rules to sort out data quality issues. While these rules might help with data integration issues, DQS is not limited to cleaning those columns which are being used to match data sets. Rules can be set up to replace values in a certain column with another value, for instance - so perhaps there's a common data entry error that gets made in a system. When the issue is noticed, a rule can be set up to always replace that particular string with another string.

SSIS can be used with MDS and DQS, in cases where you need the functionality of more than one of them. Here's a Microsoft tutorial which goes through how they can be used alongside one another.

Of course, you might opt to implement master data functionality yourself - it's not a new concept, MDS is just Microsoft's semi-automated master data offering. For many organizations, the data warehouse (or at least one layer of it) is the store of master data. Likewise, DQS is just a data quality tool, but you might opt to set up your own data quality processes. If you're using the Microsoft stack, then the more you do yourself, the more you'll probably end up using SSIS.

Title: Compare SSIS and MDS/DQS


问:
In Agile, what do you do with a severly underpointed story?
Our team is pretty good at planning/pointing, but once in a blue moon, we will have a severely underpointed story. I'm talking something we thought it would take a couple days and we realize its going to take the whole sprint. What is the recommended approach to fix this when we realize our error so that it doesn't make our velocity unusable for the next sprint planning?</p>

答:
Your actions should be determined by whether the decrease in velocity due to an underestimated story is a one-time or rare excursion, or a trend suggesting your development process needs refactoring.

You need better metrics to detect the difference. IMO, computing the average velocity over just the last two sprints is not sufficient. You should be collecting over all previous sprints to detect long term trends.

At the start of a project, the team's effort estimates will likely be in error from the actual effort. The velocity from sprint to sprint can be expected to show large fluctuations.  As the team gets more familiar with  the project tasks and better at  estimation, there should be less fluctuation and the velocity should converge to a consistent sustainable value with smaller range of variation. In statistical terms, the standard deviation of velocity should start out a fairly large fraction of the velocity, but converge to a fairly small fraction of the velocity.

If your velocity is showing large fluctuations from sprint to sprint consistently, this suggests your estimation process needs improvement.  There are many actions you might take, depending on the specifics of your program. Is it a matter of training the developers to do estimation better, is it a matter of better understanding of the problem domain, are there political issues making the estimation process unreliable? All of these and more are possibilities.

If this is not the case and your velocity has converged, but the underestimated story is a one time excursion: that  doesn't make your overall moving averaged velocity unusable for the next  sprint.

What it does do is make the estimate of your outlier story's relative contribution to the velocity too small.

You need to re-estimate the contribution of the outlier story to the velocity of the next sprint, scaling it up by a factor that takes into account the mis-estimate. Then you must make adjustments to the sprint to keep the velocity at your sustainable value.

This can mean pushing other stories to the backlog if the underestimated story has a higher priority or splitting the story into smaller stories to tackle over multiple sprints if other stories can't be pushed to the backlog.

ContentLicense: CC BY-SA 3.0


问:
Why do programs use call stacks, if nested function calls can be inlined?
Why not have the compiler take a program like this:

```<code>function a(b) { return b^2 };
function c(b) { return a(b) + 5 };
</code>```

and convert it into a program like this:

```<code>function c(b) { return b^2 + 5 };
</code>```

thereby eliminating the computer's need to remember c(b)'s return address?

I suppose the increased hard disk space and RAM needed to store the program and support its compilation (respectively) is the reason why we use call stacks. Is that correct?

答:
Inlining (replacing function calls with equivalent functionality) works well as an optimization strategy for small simple functions. The overhead of a function call can be effectively traded off for a small penalty in added program size (or in some cases, no penalty at all).

However, large functions which in turn call other functions could lead to an enormous explosion in program size if everything was inlined.

The whole point of callable functions is to facilitate efficient re-use, not just by the programmer, but by the machine itself, and that includes properties like reasonable memory or on-disk footprint.

For what it's worth: you can have callable functions without a call stack. For example: IBM System/360. When programming in languages such as FORTRAN on that hardware, the program counter (return address) would be saved into a small section of memory reserved just ahead of the function entry point. It allows for re-useable functions, but does not allow for recursion or multi-threaded code (an attempt at a recursive or re-entrant call would result in a previously saved  return address being overwritten).

As explained by other answers, stacks are good things. They facilitate recursion and multi-threaded calls. While any algorithm coded to use recursion could be coded without relying on recursion, the result may be more complex, more difficult to maintain, and may be less efficient. I'm not sure a stack-less architecture could support multi-threading at all.


问:
Is there a way to do bitwise operation with more than two state
I know how make bit operation. I'm wondering if you need more than 2 states is there a way to do it using bit instead of array and % operators. Because those are really slow.

So in case the array save state for 4 semaphores {0,1,2}

0000 + 0001 = 0001

  0001 + 0001 = 0002

  0002 + 0001 = 0000

  0002 + 2002 = 2001

Now i can do

```<code>int[] a = new int[4]{0,0,0,2};
int[] b = new int[4]{0,0,0,2};

for (int i=0; i < a.length; i++) {
   a[i] = (a[i] + b[i]) % 3;
}
</code>```

What is the best way to do this?

答:
You can stack bits together to keep track of any number of state values as you need.

If you need to keep track of 4 state values then use 2 bits.

Each bit gives you 2 values. 2 bits gives you 2x2.

I am not sure why you have lumped together array operators and % as if they are the same category of operation. % is a a modulo operator. I wouldn't consider that operator to be slow.

Of course stacking bits can result in expressions that can seem complex, but what is the priority? Is it readability or performance? Do you want to be efficient in the use of space to store your data?

To use data organised as 2 bit elements, the 4-int array you have got will be replaced by just one int.

On most systems int will be at least 2 bytes--so that's more than enough to hold 4 2-bit values (or "semaphores" as you say).

You would do well to confirm what the size of int is on your system.

And you can try this code:

```<code>int a = 0b10000000; // 4x2 bit value equivalent to: new int[4]{0,0,0,2};
int b = 0b00000011; // first item value is 3
size_data = 4;

for (int i=0; i < size_data; i++) {
   // expression: i*2 gives index for shr
   //             a >> i*2 & 0x03 gives the value of a
   //             b >> i*2 & 0x03 gives the value of b
   printf("i=%d   i*2=%d   a=%d b=%d\n", i*2, a >> i*2 & 0x03, b >> i*2 & 0x03);
}
</code>```

Body:
You can stack bits together to keep track of any number of state values as you need.

If you need to keep track of 4 state values then use 2 bits.

Each bit gives you 2 values. 2 bits gives you 2x2.

I am not sure why you have lumped together array operators and % as if they are the same category of operation. % is a a modulo operator. I wouldn't consider that operator to be slow.

Of course stacking bits can result in expressions that can seem complex, but what is the priority? Is it readability or performance? Do you want to be efficient in the use of space to store your data?

To use data organised as 2 bit elements, the 4-int array you have got will be replaced by just one int.

On most systems int will be at least 2 bytes--so that's more than enough to hold 4 2-bit values (or "semaphores" as you say).

You would do well to confirm what the size of int is on your system.

And you can try this code:

int a = 0b10000000; // 4x2 bit value equivalent to: new int[4]{0,0,0,2};
int b = 0b00000011; // first item value is 3
size_data = 4;

for (int i=0; i < size_data; i++) {
   // expression: i*2 gives index for shr
   //             a >> i*2 & 0x03 gives the value of a
   //             b >> i*2 & 0x03 gives the value of b
   printf("i=%d   i*2=%d   a=%d b=%d\n", i*2, a >> i*2 & 0x03, b >> i*2 & 0x03);
}


答:
Stacks allow us to elegantly bypass the limits imposed by the finite number of registers.

Imagine having exactly 26 globals "registers a-z" (or even having only the 7 byte-sized registers of the 8080 chip)
And every function you write in this app shares this flat list.

A naive start would be to allocate the first few registers to the first function, and knowing that it took only 3, start with "d" for the second function...
You run out quickly.

Instead, if you have a metaphorical tape, like the turing machine, you could have each function start a "call another function" by saving all the variables it's using and forward() the tape, and then the callee function can muddle with as many registers as it wants.  When the callee is finished, it returns control to the parent function, who knows where to snag the callee's output as needed, and then plays the tape backwards to restore its state.

Your basic call frame is just that, and are created and dropped by standardized machine code sequences the compiler puts in around the transitions from one function to another. (It's been a long time since I had to remember my C stack frames, but you can read up on the various ways the duties of who drops what at X86_calling_conventions.)

(recursion is awesome, but if you'd ever had to juggle registers without a stack, then you'd really appreciate stacks.)

I suppose the increased hard disk space and RAM needed to store the program and support its compilation (respectively) is the reason why we use call stacks. Is that correct?

While we can inline more these days, ("more speed" is always good; "fewer kb of assembly" means very little in a world of video streams)
The main limitation is in the compiler's ability to flatten across certain types of code patterns.

For example, polymorphic objects -- if you don't know the one and only type of object you'll be handed, you can't flatten; you have to look at the object's vtable of features and call through that pointer... trivial to do at runtime, impossible to inline at compile time.

A modern toolchain can happily inline a polymorphically-defined function when it has flattened enough of the caller(s) to know exactly which flavor of obj is:

class Base {
    public: void act() = 0;
};
class Child1: public Base {
    public: void act() {};
};
void ActOn(Base* something) {
    something->act();
}
void InlineMe() {
    Child1 thingamabob;
    ActOn(&thingamabob);
}
```

in the above, the compiler can choose to keep right on statically inlining, from InlineMe through whatever's inside act(), nor a need to touch any vtables at runtime.

But any uncertainty in what flavor of object will leave it as a call to a discrete function, even if some other invocations of the same function are inlined.

Title: Why do programs use call stacks, if nested function calls can be inlined?

Body:
Why not have the compiler take a program like this:

```<code>function a(b) { return b^2 };
function c(b) { return a(b) + 5 };
</code>```

and convert it into a program like this:

```<code>function c(b) { return b^2 + 5 };
</code>```

thereby eliminating the computer's need to remember c(b)'s return address?

I suppose the increased hard disk space and RAM needed to store the program and support its compilation (respectively) is the reason why we use call stacks. Is that correct?

Body:
Stacks allow us to elegantly bypass the limits imposed by the finite number of registers.

Imagine having exactly 26 globals "registers a-z" (or even having only the 7 byte-sized registers of the 8080 chip)
And every function you write in this app shares this flat list.

A naive start would be to allocate the first few registers to the first function, and knowing that it took only 3, start with "d" for the second function...
You run out quickly.

Instead, if you have a metaphorical tape, like the turing machine, you could have each function start a "call another function" by saving all the variables it's using and forward() the tape, and then the callee function can muddle with as many registers as it wants.  When the callee is finished, it returns control to the parent function, who knows where to snag the callee's output as needed, and then plays the tape backwards to restore its state.

Your basic call frame is just that, and are created and dropped by standardized machine code sequences the compiler puts in around the transitions from one function to another. (It's been a long time since I had to remember my C stack frames, but you can read up on the various ways the duties of who drops what at X86_calling_conventions.)

(recursion is awesome, but if you'd ever had to juggle registers without a stack, then you'd really appreciate stacks.)

I suppose the increased hard disk space and RAM needed to store the program and support its compilation (respectively) is the reason why we use call stacks. Is that correct?

While we can inline more these days, ("more speed" is always good; "fewer kb of assembly" means very little in a world of video streams)
The main limitation is in the compiler's ability to flatten across certain types of code patterns.

For example, polymorphic objects -- if you don't know the one and only type of object you'll be handed, you can't flatten; you have to look at the object's vtable of features and call through that pointer... trivial to do at runtime, impossible to inline at compile time.

A modern toolchain can happily inline a polymorphically-defined function when it has flattened enough of the caller(s) to know exactly which flavor of obj is:

class Base {
    public: void act() = 0;
};
class Child1: public Base {
    public: void act() {};
};
void ActOn(Base* something) {
    something->act();
}
void InlineMe() {
    Child1 thingamabob;
    ActOn(&thingamabob);
}

in the above, the compiler can choose to keep right on statically inlining, from InlineMe through whatever's inside act(), nor a need to touch any vtables at runtime.

But any uncertainty in what flavor of object will leave it as a call to a discrete function, even if some other invocations of the same function are inlined.


问:
Is it still a good practice to log parameters and returns?
Just a context, I am currently making a base code for a Java Spring Boot Application.

I am currently setting up the logging of the application and I stumbled upong this url and found it helpful. Although it is a little bit outdated.

Questions

In the url, 7) Log method arguments and return values, is this still relevant today? Should I manually do it in my methods?

In an MVC application, should I do it in all layers? (Controllers, Services, and DAOs)?

答:
I don't think that article is implying that every method should should be logged that way, it's just saying when you're logging make sure you capture the context in which the log occurred.

For example, if you have a log which says only "User cannot be found", if you're actually trying to understand the scenario which lead to that log then you probably need to know the user ID at least. Typically function arguments have the most significant affect on the output of a function so that's the most important context to capture, but class or global variables might also be just as important depending on the situation.

In the case of a Spring web application, I definitely wouldn't be putting logging in every single function, but I would be logging where failures are likely. For example, if you make a call to an external service.

The article itself states:

Of course, you must be reasonable but every method that: accesses
  external system (including database), blocks, waits, etc. should be
  considered.

Although, some of this logging might already be provided by your ORM or RDBMS so I wouldn't go adding logging to every single database call either.

The article also states:

You should consider DEBUG or TRACE levels as best suited for these
  types of logs.

Which typically aren't logged in production, so you might consider it an alternative to temporary print/echo statements during development. Again, only where appropriate.


答:
Are you ever going to use the information logged?

It could be possibly be useful for debugging but then you will probably use a debugger anyway.

I have worked on projects where practicality everything was logged, but there was a real business requirement -- they needed forensic proof if bad/fraudulent behavior by "trusted" associates was detected.

Title: Is it still a good practice to log parameters and returns?

Body:
Just a context, I am currently making a base code for a Java Spring Boot Application.

I am currently setting up the logging of the application and I stumbled upong this url and found it helpful. Although it is a little bit outdated.

Questions

In the url, 7) Log method arguments and return values, is this still relevant today? Should I manually do it in my methods?

In an MVC application, should I do it in all layers? (Controllers, Services, and DAOs)?


问:
Should dependency inversion be used only with Adapters everywhere?
As I understand the purpose of DI is that I can easily swap a lower level implementation. But it forces the lower level abstraction to be defined inside the higher level.

A lower level becomes dependent on the abstraction defined in the higher level and can't be used without it. But what if I would ever want to reuse my lower-level Logger class in another application?

Should I use Adapter everywhere with DI? In my example Adapter could implement ILogger interface from the higher-level code and reroute calls to the Logger class which now becomes reusable and independent from my application.

Is it a good approach?

答:
Some time passed and now I think that I can answer myself.

There is no sense to make an adapter when two interacting classes are located in the same dll. For such case it makes the code more complicated and difficult for refactoring but does not provide any benefits. If you want to reuse some functionality you still need to reference the whole dll so don't bother.

Each component (regardless of whether it's lower- or higher-level) should depend on abstractions (with only methods that it needs) which can be declared beside or in the same dll (if they are shared between multiple components).

There should be a special "setup" system which provides adapters and factories. Because no class knows about its dependencies implementation we need this system to construct objects and connect all solution parts together.


答:
But it forces the lower level abstraction to be defined inside the higher level.

No, it does not enforce this. The "lower level abstraction" (the interface, like ILogger in your example) can be defined outside the "lower level" and the "higher level" component, it can reside in a third, independ DLL which serves only for the purpose of providing the interfaces. This component is neither part of the lower nor the higher level component.

Actually, I wrote "it can", because that is not the only possible design alternative. The other two alternatives (the one you suggested: ILogger in the higher level component, and the one suggested by @KilianFoth, ILogger as part of the Logger component), are also valid approaches, with the benefit that you need less DLLs/components, but also some drawbacks regarding to the resulting dependencies or restrictions on reusability. Putting the ILogger interface into the Logger DLL imposes that your "higher level component" still has to depend on the lower level Logger component, of course, but it still leaves you the option to replace the Logger object in your higher level component by a "test logger" for unit testing purposes, as long as you don't mind your test code having a linkage dependency  to the Logger DLL.

A lower level becomes dependent on the abstraction defined in the higher level and can't be used without it.

No, it becomes dependent on the interface component. You cannot use the logger without that interface component, of course. But you can reuse the logger DLL in conjuction with the ILogger DLL in a completely separate project.

In my example Adapter could implement ILogger interface from the higher-level code and reroute calls to the Logger class which now becomes reusable and independent from my application.

The typical usage scenario of an adapter is when you have incompatible interfaces and cannot easily modify the existing code. For example, where your higher level component BusinessCalculator expects a injected BLogger (an interface, maybe defined in the DLL where BusinessCalculator lives, with some special requirements). Your standard Logger component which you have already used in five other projects and for which you are not going to change the design, resides in your "Reusable Logger" DLL and provides only an incompatible ILogger interface (maybe directly defined in your Logger DLL, maybe defined in a separate interface DLL). Then you need an adapter class which maps the BLogger calls to ILogger.

By the latter design, you can indeed decouple the BusinessCalculator and Logger components completely, only the adapter will depend on the DLLs where BLogger and ILogger are defined. Technically, it is not even clear any more which of the two is the more "higher level" or "lower level" component. The drawback is the additional overhead for managing all those different interfaces and components.

Title: Should dependency inversion be used only with Adapters everywhere?

Body:
As I understand the purpose of DI is that I can easily swap a lower level implementation. But it forces the lower level abstraction to be defined inside the higher level.

A lower level becomes dependent on the abstraction defined in the higher level and can't be used without it. But what if I would ever want to reuse my lower-level Logger class in another application?

Should I use Adapter everywhere with DI? In my example Adapter could implement ILogger interface from the higher-level code and reroute calls to the Logger class which now becomes reusable and independent from my application.

Is it a good approach?


问:
How to use git for projects which has shared files
Our team uses shared folders (Windows) to work on projects together.
We never make local copies, but always edit the files in-place.
Now I've heard we would be much better off using git.
Is git a reasonable option is this case? And if so, how can we use it?</p>

答:
Your situation today:

Our team uses shared folders (Windows) to work on projects together. We never make local copies, but always edit the files in-place.

One Source

No versioning

No chance to even detect what is called merge conflicts. What you play is »last saved wins« You have to put social constraints like »Okay, we agree never to edit the same file«. That is weak.

So in general any VCS (Version Control System) would be a benefit.

Now I've heard we would be much better off using git. Is git a reasonable option is this case? And if so, how can we use it?

Yes, git is one choice, but there are others (plastic-scm, mercurial, bazaar, SVN to name some).

These are the main benefits for your current scenario (not everything is exclusive to git):

git allows you easily to branch off something for development purposes
Think of it as follows: git remembers (like bookmarking) where you were with your work at a certain point of time. And from there you could apply changes to that. If you successfully end your work, you could merge your work into the main branch. If you are unhappy, you could revert to any previous state or throw your branch away.

as previously said, changes, which were branched off at some point, could be merged together at some time, conflicts will be shown.

you have a history of who did what and when down to the line of code.

since branching and reverting is easy, you could do more "experiments" on your codebase

no weak social constraints to solve merge conflicts

you could work offline

You may think about it.


问:
Best way to handle blank dates
I'm trying to create a contact book application, and currently I'm working on a class called Person. One of the fields of person is dateOfBirth, however I don't know how to handle unknown dates. Until now I have been using java.time.LocalDate for dateOfBirth and I've been initialising the field to null at instantiation. This isn't ideal, because it's resulting in null pointer exceptions when I try to compare dateOfBirth to other dates such as the LocalDate.now().

What would be the best way to handle dateOfBirth? Should I just create an entirely new class and manage unknown dates internally? Or is ther some better way to do it. I was going to just extend LocalDate but it's immutable so can't be extended without going to the source.

答:
Tony Hoare is said to have invented, what we now call null. And he regretted it:

I call it my billion-dollar mistake. It was the invention of the null reference in 1965. At that time, I was designing the first comprehensive type system for references in an object oriented language (ALGOL W). My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn't resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years

Source: wikipedia.

Now we have to live and deal with it.

however I don't know how to handle unknown dates.

Trust me, you are not alone.

The problem is, that there is something I would call ambiguity of information. Asking »when was the battle of waterloo?« in everyday life »I don't know« is an accepted answer. But it is not the answer about the date itself, it is about the knowledge of the speaker.

To your problem: Asking person.getBirthDate() gives you an ambigous answer:

either it was on 1952-11-02

or the equivalent to I don't know, which is null.

What is a proper solution to that misery of ambiguity?

Since, we have null and since it is widely accepted across datastores, you should use null as a correct answer in the context of the DB.

But what about your programm:

As you correctly said

because it's resulting in null pointer exceptions when I try to compare dateOfBirth to other dates such as the LocalDate.now()

You have to guard against that in some way or the other:

1) You could introduce a getter person.birthdayKnown() to do the following:

```<code>if (personA.birthdayKnown() && personA.birthdayKnown()) // allow further operations
</code>```

2) With the advent of Java8, you could make it an Optional and work with isPresent().

Title: Best way to handle blank dates

Body:
Tony Hoare is said to have invented, what we now call null. And he regretted it:

I call it my billion-dollar mistake. It was the invention of the null reference in 1965. At that time, I was designing the first comprehensive type system for references in an object oriented language (ALGOL W). My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn't resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years

Source: wikipedia.

Now we have to live and deal with it.

however I don't know how to handle unknown dates.

Trust me, you are not alone.

The problem is, that there is something I would call ambiguity of information. Asking »when was the battle of waterloo?« in everyday life »I don't know« is an accepted answer. But it is not the answer about the date itself, it is about the knowledge of the speaker.

To your problem: Asking person.getBirthDate() gives you an ambigous answer:

either it was on 1952-11-02

or the equivalent to I don't know, which is null.

What is a proper solution to that misery of ambiguity?

Since, we have null and since it is widely accepted across datastores, you should use null as a correct answer in the context of the DB.

But what about your programm:

As you correctly said

because it's resulting in null pointer exceptions when I try to compare dateOfBirth to other dates such as the LocalDate.now()

You have to guard against that in some way or the other:

1) You could introduce a getter person.birthdayKnown() to do the following:

if (personA.birthdayKnown() && personA.birthdayKnown()) // allow further operations

2) With the advent of Java8, you could make it an Optional and work with isPresent().


答:
Use the class Optional<LocalDate>

This useful container class was introduced in Java 8. It is a wrapper used for values which you might or might not know. It is unboxed with various methods which all allow you to handle the case that the value is unknown in a graceful manner.

get() unboxes the LocalDate, but throws a NoSuchElementException in case you have none. Unfortunately it is an unchecked exception, just like the dreaded NullPointerException. So I would recommend to avoid using this method and instead use:

orElseThrow(exception) which throws said exception when you don't have a value. The exception can (and should be) a checked exception so you are forced to handle it. Don't feel like writing a clunky try...catch... construct? In that case:

ifPresent(Consumer<? super T> consumer) is a useful construct when you want to execute some code only if you have a value and otherwise do nothing.

orElse(T value) unboxes the value but gets you the dummy value you provide when you have none

For more information, check the article "Tired of Null Pointer Exceptions? Consider Using Java SE 8's Optional!" on Oracle Tech Net and the documentation to see what other methods it provides.

Not using Java 8 yet?

When you are still using an older version of Java, you could easily improvise your own OptionalDate class, which has just:

private LocalDate

public void set(LocalDate value) and

public LocalDate get() throws DateUnknownException

By having the getter throw a checked exception you are forced to always handle the null-case.

Title: Best way to handle blank dates

Body:
I'm trying to create a contact book application, and currently I'm working on a class called Person. One of the fields of person is dateOfBirth, however I don't know how to handle unknown dates. Until now I have been using java.time.LocalDate for dateOfBirth and I've been initialising the field to null at instantiation. This isn't ideal, because it's resulting in null pointer exceptions when I try to compare dateOfBirth to other dates such as the LocalDate.now().

What would be the best way to handle dateOfBirth? Should I just create an entirely new class and manage unknown dates internally? Or is ther some better way to do it. I was going to just extend LocalDate but it's immutable so can't be extended without going to the source.


问:
Can I use git to replay changes for projects that use media assets rather than program source code?
So while waiting for a project to build I like to run gource and see a fun video of my team building the project over time. While I was watching me and my team fly around editing and changing the file tree a coworker who is on our media team loved the visual representation and immediately asked how I could do this for his team's media projects ( documentaries, short videos, poster design projects ) which are worked on as a team and everyone edits files individually and then pushes them up to a central server on the LAN.

I know git would freak every file change because to it the entire file is new every time they say export the video to the LAN or anything like that. But would a quick git repo be possible for a media team? How much overhead vs pay off would they expect?

答:
Git is not very will suited for this as evidenced by the fact that currently at least three different extensions exist to handle this problem git-fat, git-annex, git-media.

Svn also have the possibility to only check out only a sub folder of the repository which git was explicitly designed to NOT to do.

Since git is distributed all clones must contain all versions of all blobs which will be large for binary files since they don't compress or diff well. Svn is centralized so a checkout can checkout only the recent version.

I recommend using svn or using one of the git extensions.


问:
How to design a backend for Polymer?
I've been watching Google I/O and I have decided to try to build a small scale site with Polymer. I have some HTML,CSS & JS knowledge, but I don't have much knowledge about programming the backend, so I would like to learn some of that in the process as well.
The problem is I'm not quite sure how to approach this. When it comes to backend I'm mostly used to the server responding to requests with HTML files or so such as in PHP and I've been reading a bit about REST APIs and JSON. Also, at Google I/O they talked a lot about firebase, but I would like to create my own backend for educational purposes.

So my question is, what approach should be used for backend for polymer applications ? What is recommended ? Is there any particular language that should be used ? Should the server be returning HTML or JSON ? I'm looking for the right approach thst could be used also for a backend that could serve an android app as well as the web app in the future maybe.

I tried googling but since I don't have much experience in this area , the results hasn't been very rewarding. I would badically just like to be pointed in the right direction, I know there's usually no straight answer for this.

答:
I guess the easiest and fastest way to start would be using Node.Js, tutorial. This is a JavaScript library that runs on the server.

 If you're looking for compiled languages, then you could look at  Java with Apache tomcat

 As for the return format, I would definitely go with JSON and perform a the dedicated formatting on the client (you mentioned you want to support multiple clients)

Title: How to design a backend for Polymer?


问:
What are the cons to excluding some code from coverage analysis?
I've recently become very interested in improving my project's test coverage. At this point, I have a submodule pretty thoroughly tested, but it's coverage is still pretty low because the tool is picking up all of my views as entirely uncovered. (I'm using MVP, so these views are really "dumb", they don't need to be tested in my opinion.) Before I go slapping an [ExcludeCodeCoverage] attributes on my views, I'd like to know if there are any downsides to this.

To be clear about things, I'm only looking to do this at the class level. For example, I have a method that hits the file system. Obviously, I can't test it (easily), but I consider the fact that I can't test it a smell. Since it's a smell, the reduced coverage on this class is an alert to me that there's something in need of refactoring. I will not be excluding anything "just to get the numbers up". I'm just interested potential pitfalls of excluding the UI layer and simple class factories like this.

```<code>public class SourceControlProviderFactory : ISourceControlProviderFactory
{
    public ISourceControlProvider CreateProvider(VBProject project)
    {
        return new GitProvider(project);
    }

    public ISourceControlProvider CreateProvider(VBProject project, IRepository repository)
    {
        return new GitProvider(project, repository);
    }
}
</code>```

This question is closely related, but I've already targeted the code I'd like to exclude. I'm more interested in "Are there good reasons not to do this?" as opposed to "What should I exclude?".

答:
What are the cons to excluding some code from coverage analysis?

You don't get to see that code in your code coverage report. So if the coverage changes, you won't know about it (from this tool), so you won't fix it.

Some of your... less disciplined programmers (which may be you in the future) will be more inclined to exclude code if they see other places which are excluded.

But the attribute is there for a reason. Some code, you just don't care if it has test coverage because it's obviously correct, or because it clutters up your report, making it harder to see things that actually are missing coverage. So use it judiciously, and make sure that others do as well.


问:
Determinining "value" in multi-agent microeconomical simulation
I am trying to determine an objective way for a self-interested agent to calculate the optimal buying/selling price for goods in a multi-agent simulation not dissimilar to Sugarscape (http://en.wikipedia.org/wiki/Sugarscape). The simulation is as follows:

Each agent has a stock of food F, a stock of money G, a certain amount of "energy", E, and a position (x, y) on a square grid. Moving from one square to a neighboring square expends A units of energy, and energy is naturally expended at a rate of B units per simulation day. An agent has the following options available to it during each day: consume a unit of food to increase its energy by Q units; move to another location (provided it has sufficient energy), "forage" for food (expend P units of energy to obtain a [possibly unknown] quantity of food), or trade with a neighboring agent for a mutually-agreeable price.

Each agent's goal is to maximize its "utility function" U(E, F, G) without regard for that of other agents.

Right away, this seems to give a base "use value" of food: Vuse = U(E + Q, F - 1, G) - U(E, F, G), but if this was the whole story, this wouldn't be an interesting problem.

It seems the most general (but exponential-time) solution would look something like this:

```<code>Function SearchActions(State S):
    Add(consume food) to action set
    Add(forage for food) to action set
    For each other agent A
        For each possible trading price P
            Add(trade with A at price P) to action set
    For each action X in action set
        S' = Apply X to S
        SearchActions(S')
    Return optimal X
End function
</code>```

However, the major difficulty gets swept under the rug by "for each possible price", because the price that agent A will buy/sell for is itself dependent on an identical calculation...e.g.

My calculation of the value depends on either what I can get from using it myself, or what someone else will pay for it...but what they will pay for it depends on what I will pay for it.

How do you cut this knot?

I know this problem has been solved before...but I cannot find any references to it, let alone any actual implementations. The closest I've come has been a paper about "Strategic Planning" in SugarScape, but it only seems to give the results of the planning, rather than explaining how the planning is done.

答:
I have my own implementation of Sugarscape and here's how I addressed the problem. My implementation with source code can be found at http://sugarscape.sourceforge.net/. Note, the implementation requires a JRE install to run within the browser. Alternately you can run it locally using the Jave AppletViewer.

Here's my take on this issue based on my implementation. Agents have two sources of food, Sugar & Spice. They also have consumption requirements (metabolism) for both items. An internal value is determined by each agent based on how many cycles their current stocks will allow them to survive. So if the agent has the following base values,

```<code>Agent x has 15 units of sugar and needs to consume 3 sugar units to survive each cycle.
Agent x has 30 units of spice and needs to consume 2 spice units to survive each cycle.
</code>```

Their calculations go as described below,

```<code>Sugar Metabolic Rate (SuM) = 15 / 3 = 5.
Spice Metabolic Rate (SpM) = 30 / 2 = 15.

Time Until Death = Minimum of (SuM, SpM)

Marginal Rate of Substitution (MRS) = SpM / SuM
</code>```

...MRS results less than 1 signify a preference for spice, results greater than 1 conversely    indicate a preference for sugar.

Calculate Surplus:

```<code>if( MRS > 1  )
{   surplus = SpiceStocks - (SpiceMetabolism * TUD);
    //If surplus <= metabolism Then Set surplus to Zero
    surplus = surplus > (SpiceMetabolism * 2) ? surplus : 0;
}
else if( MRS < 1  )
{   surplus = SugarStocks - (SugarMetabolism * TUD);
    //If surplus <= metabolism Then Set surplus to Zero
    surplus = surplus > (SugarMetabolism * 2) ? surplus : 0;
}
else
    surplus = 0;    //MRS == 1,
</code>```

Once these calculations are determined, a list of potential trading partners is constructed by examining the adjoining cells for agents with a different MRS.

The list is sorted by the MRS gap between the agent & each trading partner.

A trade is consumated with the trading partner that has the highest MRS gap in relation to our agent. Multiple trades until the available surplus is consumed may be allowed within each cycle.

The surplus to be traded is the lower of the 2 surpluses between agent and trading partner.

```<code>BarterPrice = Squareroot( Agent MRS * Trading Partner MRS );
</code>```

I know this answer is a bit late but I am hoping it helps the next person looking to implement this wonderful simulation.

Body:
I have my own implementation of Sugarscape and here's how I addressed the problem. My implementation with source code can be found at http://sugarscape.sourceforge.net/. Note, the implementation requires a JRE install to run within the browser. Alternately you can run it locally using the Jave AppletViewer.

Here's my take on this issue based on my implementation. Agents have two sources of food, Sugar & Spice. They also have consumption requirements (metabolism) for both items. An internal value is determined by each agent based on how many cycles their current stocks will allow them to survive. So if the agent has the following base values,

Agent x has 15 units of sugar and needs to consume 3 sugar units to survive each cycle.
Agent x has 30 units of spice and needs to consume 2 spice units to survive each cycle.

Their calculations go as described below,

Sugar Metabolic Rate (SuM) = 15 / 3 = 5.
Spice Metabolic Rate (SpM) = 30 / 2 = 15.

Time Until Death = Minimum of (SuM, SpM)

Marginal Rate of Substitution (MRS) = SpM / SuM

...MRS results less than 1 signify a preference for spice, results greater than 1 conversely    indicate a preference for sugar.

Calculate Surplus:

if( MRS > 1  )
{   surplus = SpiceStocks - (SpiceMetabolism * TUD);
    //If surplus <= metabolism Then Set surplus to Zero
    surplus = surplus > (SpiceMetabolism * 2) ? surplus : 0;
}
else if( MRS < 1  )
{   surplus = SugarStocks - (SugarMetabolism * TUD);
    //If surplus <= metabolism Then Set surplus to Zero
    surplus = surplus > (SugarMetabolism * 2) ? surplus : 0;
}
else
    surplus = 0;    //MRS == 1,

Once these calculations are determined, a list of potential trading partners is constructed by examining the adjoining cells for agents with a different MRS.

The list is sorted by the MRS gap between the agent & each trading partner.

A trade is consumated with the trading partner that has the highest MRS gap in relation to our agent. Multiple trades until the available surplus is consumed may be allowed within each cycle.

The surplus to be traded is the lower of the 2 surpluses between agent and trading partner.

BarterPrice = Squareroot( Agent MRS * Trading Partner MRS );

I know this answer is a bit late but I am hoping it helps the next person looking to implement this wonderful simulation.


答:
As @Philipp said, Optional is a good answer to this problem. However, it requires Java 8 (even if you can implement it yourself), and this kind of structure is typically adapted for functional programming style, and could therefore seem strange in a object oriented system.

A typical OOP alternative is Null Object. See for instance my answer on this other post. It allows you to define a "default behaviour" when the object is not set, which is what you want.

Title: Best way to handle blank dates


问:
Injection, strategies and OO
I'm working on refactoring a project. The business logic looks very much like using the Strategy pattern would be very beneficial, because depending on the values of three properties (let's say age, gender and salary), a different policy of discount and validation is applied.

My first idea was to put the logic responsible for deciding which policy to apply into a StrategyFactory, and have it return a different implementation of a Strategy interface. My concern is related to where to and where not to use DI. The StrategyFactory will need some DI to call other services, as will some, but not all of the strategy objects.

So in the end, I have to either annotate almost everything as a @Service/@Component or have the Factory send the services to the strategies via parameter, what looks even worse.

Am I missing something or is this normal? Could it be that the application layers are too tangled? Is this not the right case/way to use the strategy pattern?

I just need a brief answer to if there is anything that sounds very obviously wrong.

答:
In original Strategy pattern a strategy is injected into consumer. The code that is creating both consumer and strategy is responsible for choosing appropriate strategy. It is easier so if you can you should better stick to this approach.

However, your problem is not uncommon - strategy has to be chosen in runtime based on input parameters. I see here two aspects:

creation of strategies

choosing appropriate strategy based on parameters

The first one is technical detail and the second one is usually application logic rule. Both aspects should be separated (see Single responsibility principle).

It is perfectly fine to delegate creation of objects (including strategies) to Dependency Injection framework (e.g. by using Spring @Component annotations, although I prefer Java based configuration which separates object creation and application logic even more).

The second aspect, choosing a strategy, can be implemented in separate class, like StrategyChooser. Such class can also be created by DI framework and specific strategies can be injected. Based on parameters the class can decide which strategy to use. I would not call this class Factory as Factory pattern is about object creation, which is not the case here.

Title: Injection, strategies and OO


问:
Usage of MVVM in iOS
I'm an iOS developer and I'm guilty of having Massive View Controllers in my projects so I've been searching for a better way to structure my projects and came across the MVVM (Model-View-ViewModel) architecture. I've been reading a lot of MVVM with iOS and I have a couple of questions. I'll explain my issues with an example.

I have a view controller called LoginViewController.

LoginViewController.swift

```<code>import UIKit

class LoginViewController: UIViewController {

    @IBOutlet private var usernameTextField: UITextField!
    @IBOutlet private var passwordTextField: UITextField!

    private let loginViewModel = LoginViewModel()

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    @IBAction func loginButtonPressed(sender: UIButton) {
        loginViewModel.login()
    }
}
</code>```

It doesn't have a Model class. But I did create a view model called LoginViewModel to put the validation logic and network calls.

LoginViewModel.swift

```<code>import Foundation

class LoginViewModel {

    var username: String?
    var password: String?

    init(username: String? = nil, password: String? = nil) {
        self.username = username
        self.password = password
    }

    func validate() {
        if username == nil || password == nil {
            // Show the user an alert with the error
        }
    }

    func login() {
        // Call the login() method in ApiHandler
        let api = ApiHandler()
        api.login(username!, password: password!, success: { (data) -> Void in
            // Go to the next view controller
        }) { (error) -> Void in
            // Show the user an alert with the error
        }
    }
}
</code>```

My first question is simply is my MVVM implementation correct? I have this doubt because for example I put the login button's tap event (loginButtonPressed) in the controller. I didn't create a separate view for the login screen because it has only a couple of textfields and a button. Is it acceptable for the controller to have event methods tied to UI elements?

My next question is also about the login button. When the user taps the button, the username and password values should gte passed into the LoginViewModel for validation and if successful, then to the API call. My question how to pass the values to the view model. Should I add two parameters to the login() method and pass them when I call it from the view controller? Or should I declare properties for them in the view model and set their values from the view controller? Which one is acceptable in MVVM?

Take the validate() method in the view model. The user should be notified if either of them are empty. That means after the checking, the result should be returned to the view controller to take necessary actions (show an alert). Same thing with the login() method. Alert the user if the request fails or go to the next view controller if it succeeds. How do I notify the controller of these events from the view model? Is it possible to use binding mechanisms like KVO in cases like this?

What are the other binding mechanisms when using MVVM for iOS? KVO is one. But I read it's not quite suitable for larger projects because it require a lot of boilerplate code (registering/unregistering observers etc). What are other options? I know ReactiveCocoa is a framework used for this but I'm looking to see if there are any other native ones.

All the materials I came across on MVVM on the Internet provided little to no information on these parts I'm looking to clarify, so I'd really appreciate your responses.

答:
I am only just approaching these questions myself but I will give the best answers I can and make some observations.

We are told that iOS' MVC expects us to break our program up into models, views and controllers which link specific views to specific models. Sadly, in practice we will have a number of views and a number of models but only one (View)Controller taking care of all the linkages. This is what leads to massive ViewControllers.

Adopting MVVM in this context means breaking the ViewController up into two parts. The part that deals directly with Views (which stays in the ViewController class proper,) and the part that deals directly with Models (which is moved into the ModelView class/struct.)

This means that only the ViewController should be sending/receiving messages from/to the Views and the only non-view object the VC should be conversing with is the ModelView. While the ModelView should be conversing with all the various Model objects and should never converse with a View.

The above notion of the ViewController/ViewModel split leeds to the following answers to your questions:

No, your MVVM implementation is not correct. Your ViewModel methods have a fundamental flaw. They should not be talking directly with any view objects so they aren't in charge of showing the user any alerts. That's the ViewController's job. The ViewModel also isn't in charge of transitioning between ViewControllers.

The ViewController should not be dealing with any model objects. It should only be conversing with Views and the ModelView. Therefore, the ViewController should not be pulling the username and password out of it's views and passing them to the ViewModel's login function. That would require the ViewController to understand something about the differences between Usernames and Passwords and when it is appropriate to use them.

Instead, the ViewController should inform the ViewModel when changes occur in the username and password fields. It should inform the ViewModel when the login button is pressed. It shouldn't have any knowledge about what model objects the viewModel needs in any particular method.

I would expect the validate() function to return a Bool (better to call it isValid and make it a computed property.) I would expect the login() function to accept two blocks (one for pass and one for fail.) It can communicate what happened by calling the correct block. Another option would be to have the function accept one block as a parameter with a success boolean. So something like this:

-

```<code>struct LoginViewModel {

    var username: String = ""
    var password: String = ""

    init(username: String, password: String) {
        self.username = username
        self.password = password
    }

    var isValid: Bool {
        return !username.isEmpty && !password.isEmpty
    }

    func login(callback: (error: NSError?) -> Void) {
        let api = ApiHandler()
        api.login(username, password: password, success: { (data) -> Void in
            callback(error: nil)
            }) { (error) -> Void in
                callback(error: error)
        }
    }

}
</code>```

In the MVVM paradigm, ReactiveCocoa (and RxSwift is another library) are used to communicate changes in the ModelView back to the ViewController, but let me ask you this... Does your ModelView ever change in any substantive way that your ViewController doesn't know about? So far, I have not been in a situation where any other object is sending messages to my ModelView other than the ViewController it is attached to, so there isn't any way for the ModelView to mutate without the ViewController knowing it's at least possible. Because of this, I generally have an updateUI() function in my ViewController. Every time my ViewController sends a potentially mutating message to the ModelView, it then calls updateUI() which examines the ViewModel and updates the UI accordingly. No need for any tricks.

-
Hope this helps you and hopefully my answer will stimulate some discussion on this question.

Title: Usage of MVVM in iOS

Body:
I am only just approaching these questions myself but I will give the best answers I can and make some observations.

We are told that iOS' MVC expects us to break our program up into models, views and controllers which link specific views to specific models. Sadly, in practice we will have a number of views and a number of models but only one (View)Controller taking care of all the linkages. This is what leads to massive ViewControllers.

Adopting MVVM in this context means breaking the ViewController up into two parts. The part that deals directly with Views (which stays in the ViewController class proper,) and the part that deals directly with Models (which is moved into the ModelView class/struct.)

This means that only the ViewController should be sending/receiving messages from/to the Views and the only non-view object the VC should be conversing with is the ModelView. While the ModelView should be conversing with all the various Model objects and should never converse with a View.

The above notion of the ViewController/ViewModel split leeds to the following answers to your questions:

No, your MVVM implementation is not correct. Your ViewModel methods have a fundamental flaw. They should not be talking directly with any view objects so they aren't in charge of showing the user any alerts. That's the ViewController's job. The ViewModel also isn't in charge of transitioning between ViewControllers.

The ViewController should not be dealing with any model objects. It should only be conversing with Views and the ModelView. Therefore, the ViewController should not be pulling the username and password out of it's views and passing them to the ViewModel's login function. That would require the ViewController to understand something about the differences between Usernames and Passwords and when it is appropriate to use them.

Instead, the ViewController should inform the ViewModel when changes occur in the username and password fields. It should inform the ViewModel when the login button is pressed. It shouldn't have any knowledge about what model objects the viewModel needs in any particular method.

I would expect the validate() function to return a Bool (better to call it isValid and make it a computed property.) I would expect the login() function to accept two blocks (one for pass and one for fail.) It can communicate what happened by calling the correct block. Another option would be to have the function accept one block as a parameter with a success boolean. So something like this:

-

struct LoginViewModel {

    var username: String = ""
    var password: String = ""

    init(username: String, password: String) {
        self.username = username
        self.password = password
    }

    var isValid: Bool {
        return !username.isEmpty && !password.isEmpty
    }

    func login(callback: (error: NSError?) -> Void) {
        let api = ApiHandler()
        api.login(username, password: password, success: { (data) -> Void in
            callback(error: nil)
            }) { (error) -> Void in
                callback(error: error)
        }
    }

}

In the MVVM paradigm, ReactiveCocoa (and RxSwift is another library) are used to communicate changes in the ModelView back to the ViewController, but let me ask you this... Does your ModelView ever change in any substantive way that your ViewController doesn't know about? So far, I have not been in a situation where any other object is sending messages to my ModelView other than the ViewController it is attached to, so there isn't any way for the ModelView to mutate without the ViewController knowing it's at least possible. Because of this, I generally have an updateUI() function in my ViewController. Every time my ViewController sends a potentially mutating message to the ModelView, it then calls updateUI() which examines the ViewModel and updates the UI accordingly. No need for any tricks.

-
Hope this helps you and hopefully my answer will stimulate some discussion on this question.


问:
What mistakes do your users make, and how can you update your application to handle them?
In fact this question is about cautions to be taken to enhance quality user experience and reduce avoidable support calls.</p>

答:
Here is one I heard this week. A user asks for a feature "send me a notification when an event occurs". Simple enough and the developer goes ahead and implements it. Sure, the first question should have been "what are trying to address by this notification?". I won't go into that. Few days later the user stops by the developer and asks "I got this notification. What am I supposed to do with it?".

I remembered this Dilbert comic and suggested to the developer "write an app to figure out what the user should do with that notification".

Like mpeterson said, the user is very competitive in their area of expertise. They just don't think like a software developer or designer.

ContentLicense: CC BY-SA 2.5


问:
Is anything in programming truly evil?
So, there are a bunch of questions appearing asking is X evil, is Y evil.

My view is that there are no language constructs, algorithms or whatever which are evil, just ones which are badly used.  Hell, if you look hard enough there are even valid uses of goto.

So does absolute evil, that is something which is utterly incompatible with best practice in all instances, exist in programming?  And if so what is it?  Or is it just bad programmers not knowing when something is appropriate?

Edit: To be clear, I'm not talking about things programmers do (such as not checking return codes or not using version control - they're choices made by bad programmers), I mean tools, languages, statements, whatever which are just bad...

答: I'm tempted to say continuations, but I think the correct answer is that there is no objective, absolute evil in programming. On the other hand, even the best tools can be abused.</p>

Title: Is anything in programming truly evil?


问:
When not to use early return?
Nesting is unavoidable, however in most cases returning early is a more viable option.

Consider the following snippet:

MyRoutine(argument)
{
    if (0 == argument) {
         SubRoutine(argument);
    } else if (1 == argument) {
         SubRoutineForSomething(argument);
    } else {
         SubRoutineForMe(argument);
    }

    return this;
}
```

<p>I find myself constantly refactoring that to</p>

<pre class="lang-c prettyprint-override"><code>MyRoutine(argument)
{
    if (0 == argument) {
         SubRoutine(argument);

         return this;
    }

    if (1 == argument) {
         SubRoutineForSomething(argument);

         return 1;
    }

    SubRoutineForMe(argument);

    return this;
}
</code>```

Only exception is to keep things DRY, so instead of

MyRoutine(argument)
{
    if (0 == argument) {
         SubRoutine(argument);
         AnotherAction();

         return this;
    }

    if (1 == argument) {
         SubRoutineForSomething(argument);
         AnotherAction();

         return 1;
    }

    SubRoutineForMe(argument);
    AnotherAction();

    return this;
}
```

<p>I'd rather use</p>

<pre class="lang-c prettyprint-override"><code>MyRoutine(argument)
{
    if (0 == argument) {
         SubRoutine(argument);
    } else if (1 == argument) {
         SubRoutineForSomething(argument);
    } else {
         SubRoutineForMe(argument);
    }

    AnotherAction();

    return this;
}
</code>```

Are there any major disadvantages to exiting early? I'm moving from serverside work towards game development (Javascript and C-like languages). Are there any pitfalls I should watch out for/benefits I'm missing (branch prediction)?

I hope this is different than this question.

答: This may be a little bit opinionated, but I recommend using "early return" when it makes the code simpler to read, and especially when it reduces the nesting level. However, IMHO the refactored version of your first example fulfills none of those two conditions (in fact, I think in your example the readability is a little bit decreased), so that is exactly an example where it is not very beneficial to use "early return".

Title: When not to use early return?


答:
Your refactoring doesn't make much sense.  I don't see any scenario where you would return two different types, i.e. either this or an integer number, so return this is almost certainly going to go at the bottom of the if tree, and the original code is better.

In addition, if (0 == argument) is pretty much not used anymore, unless you're using a C compiler that's not smart enough to warn you when you're trying to make an unintended assignment in an if condition.

Depending on what you're actually trying to accomplish, you might be better off with something like this:

```<code>MyType MyRoutine(argument)
{
    switch(argument)
    {
        case 0: return someFunctionReturningAnInstanceOfMyType();
        case 1: return someOtherFunctionReturningAnInstanceOfMyType();
    }
    return default(myType);
}
</code>```

which is clean, simple, and always returns early, except in the default case.

Title: When not to use early return?

Body:
Nesting is unavoidable, however in most cases returning early is a more viable option.

Consider the following snippet:

MyRoutine(argument)
{
    if (0 == argument) {
         SubRoutine(argument);
    } else if (1 == argument) {
         SubRoutineForSomething(argument);
    } else {
         SubRoutineForMe(argument);
    }

    return this;
}
```

<p>I find myself constantly refactoring that to</p>

<pre class="lang-c prettyprint-override"><code>MyRoutine(argument)
{
    if (0 == argument) {
         SubRoutine(argument);

         return this;
    }

    if (1 == argument) {
         SubRoutineForSomething(argument);

         return 1;
    }

    SubRoutineForMe(argument);

    return this;
}
</code>```

Only exception is to keep things DRY, so instead of

MyRoutine(argument)
{
    if (0 == argument) {
         SubRoutine(argument);
         AnotherAction();

         return this;
    }

    if (1 == argument) {
         SubRoutineForSomething(argument);
         AnotherAction();

         return 1;
    }

    SubRoutineForMe(argument);
    AnotherAction();

    return this;
}
```

<p>I'd rather use</p>

<pre class="lang-c prettyprint-override"><code>MyRoutine(argument)
{
    if (0 == argument) {
         SubRoutine(argument);
    } else if (1 == argument) {
         SubRoutineForSomething(argument);
    } else {
         SubRoutineForMe(argument);
    }

    AnotherAction();

    return this;
}
</code>```

Are there any major disadvantages to exiting early? I'm moving from serverside work towards game development (Javascript and C-like languages). Are there any pitfalls I should watch out for/benefits I'm missing (branch prediction)?

I hope this is different than this question.

Body:
Your refactoring doesn't make much sense.  I don't see any scenario where you would return two different types, i.e. either this or an integer number, so return this is almost certainly going to go at the bottom of the if tree, and the original code is better.

In addition, if (0 == argument) is pretty much not used anymore, unless you're using a C compiler that's not smart enough to warn you when you're trying to make an unintended assignment in an if condition.

Depending on what you're actually trying to accomplish, you might be better off with something like this:

MyType MyRoutine(argument)
{
    switch(argument)
    {
        case 0: return someFunctionReturningAnInstanceOfMyType();
        case 1: return someOtherFunctionReturningAnInstanceOfMyType();
    }
    return default(myType);
}

which is clean, simple, and always returns early, except in the default case.


问:
Is "lazy loading" factories in AngularJS using this $q.defer method good practice
I guess I don't believe in myself as a good programmer but I found out this method on my own (not suggestion I'm the first one to do it, but I didn't follow a guide) so it must be broken somehow.

$q is mainly a callback kind of service for async reasons, but it served me in another way as well.

I might have multiple calls to a long running service, but I only need a response once. So I want to disregard all calls except from the first one and cache the result from that and return to everybody.

If I give everybody a promise when called they get the result when the promise is resolved, even if it was resolved before the promise was actually given, that's a nice feature.

So I could only make the dervice call the first time I give the promise.

```<code>myApp.factory('serviceWithLongCall', function ($q, $timeout) {

    var data = {}
    var hasStarted = false;
    var deferred = $q.defer();

    return {
        call: call
    };

    function call() {
        if (!hasStarted) {
            hasStarted = true;
            console.log('timeout started');
            $timeout(function () {
                console.log('timeout ended');
                data = 42;
                deferred.resolve(data);
            }, 3000);
        }

        return deferred.promise;
    }

});
</code>```

fiddle with example, click some buttons and wait for 3 seconds from first click, later clicks will happen instantly.

Is something off with this method, will I have a race condition?

答:
Returning the same promise from a call multiple times for caching reasons is absolutely fine. No race condition that I can think of, and I've used that technique with no issue.

The only small issue with you code is that's it's unnecessary to create the deferred object. $timeout returns a promise that can resolve to the value you want.

```<code>myApp.factory('serviceWithLongCall', function ($timeout) {

    var data = {}
    var promise = null;

    return {
        call: call
    };

    function call() {
        if (!promise) {
            console.log('timeout started');
            promise = $timeout(function () {
                console.log('timeout ended');
                data = 42;
                return data;
            }, 3000);
        }

        return promise;
    }
});
</code>```

Admittedly your use of $timeout might be just for example reasons, but I suspect you can do the same thing with $http.

Body:
Returning the same promise from a call multiple times for caching reasons is absolutely fine. No race condition that I can think of, and I've used that technique with no issue.

The only small issue with you code is that's it's unnecessary to create the deferred object. $timeout returns a promise that can resolve to the value you want.

myApp.factory('serviceWithLongCall', function ($timeout) {

    var data = {}
    var promise = null;

    return {
        call: call
    };

    function call() {
        if (!promise) {
            console.log('timeout started');
            promise = $timeout(function () {
                console.log('timeout ended');
                data = 42;
                return data;
            }, 3000);
        }

        return promise;
    }
});

Admittedly your use of $timeout might be just for example reasons, but I suspect you can do the same thing with $http.


答:
So does absolute evil, that is something which is utterly incompatible with best practice in all instances, exist in programming?

Of course not.  It's like asking if anything in my toolbox is evil.  My hammer is a great "good" to me, unless my four year old gets her hands on it.

Title: Is anything in programming truly evil?

Body:
So, there are a bunch of questions appearing asking is X evil, is Y evil.

My view is that there are no language constructs, algorithms or whatever which are evil, just ones which are badly used.  Hell, if you look hard enough there are even valid uses of goto.

So does absolute evil, that is something which is utterly incompatible with best practice in all instances, exist in programming?  And if so what is it?  Or is it just bad programmers not knowing when something is appropriate?

Edit: To be clear, I'm not talking about things programmers do (such as not checking return codes or not using version control - they're choices made by bad programmers), I mean tools, languages, statements, whatever which are just bad...


答:
Waiting to return until the very end of the function is very useful in languages where you must release resources before you return, because since you only have one exit point, you can be sure you're cleaning up before you leave.

In languages that have automatic garbage collection, returning early doesn't have that disadvantage. In fact, Rubocop, a static code analyzer for Ruby, encourages you to refactor methods to return early when you are checking parameters. That's called a guard clause. In my own experience, it really helps clear up nasty if/else chains in certain situations.

You say you may be programming in C-type languages as well as JavaScript. I return early in JavaScript all the time for these reasons. However you'd be better off avoiding this in C-type languages, otherwise you'd duplicate (or forget) cleanup code.

Title: When not to use early return?


问:
Compilation to bytecode vs machine code
Does compilation that produces an interim bytecode (like with Java), rather than going "all the way" to machine code, generally involve less complexity (and thus likely take less time)? </p>

答:
I would say that simplifies the compiler design since the compilation is always Java to generic virtual machine code. That also means you only need to compile the code once and it will run on any plataform (instead of having to compile on each machine). I am not so sure if the compilation time will be lower because you can consider the virtual machine just like a standardized machine.

On the other hand, each machine will have to have the Java Virtual Machine loaded so it can interpret the "byte code" (which is the virtual machine code resulted from the java code compilation), translate it to the actual machine code and run it.

Imo this is good for very big programs but very bad for small ones (because the virtual machine is a waste of memory).

Title: Compilation to bytecode vs machine code


答: Yes, compiling to Java bytecode is easier than compiling to machine code. This is partially because there's only one format to target (as Mandrill mentions, though this only reduces compiler complexity, not compile time), partly because the JVM is a much simpler machine and more convenient to program than real CPUs — as it's been designed in tandem with the Java language, most Java operations map to exactly one bytecode operation in a very simple way. Another very important reason is that practically no optimization takes place. Almost all efficiency concerns are left to the JIT compiler (or to the JVM as a whole), so the entire middle end of normal compilers disappears. It can basically walk through the AST once and generate ready-made bytecode sequences for each node. There is some "administrative overhead" of generating method tables, constant pools, etc. but that's nothing compared to the complexities of, say, LLVM.

Title: Compilation to bytecode vs machine code

Body: Does compilation that produces an interim bytecode (like with Java), rather than going "all the way" to machine code, generally involve less complexity (and thus likely take less time)? </p>


答:
A compiler is simply a program that takes human-readable1 text files and translates them into binary instructions for a machine. If you take a step back and think about your question from this theoretical perspective, the complexity is roughly the same. However, on a more practical level, byte code compilers are simpler.

What broad steps have to happen to compile a program?

Scanning, parsing and validating source code.

Converting source to an abstract syntax tree.

Optional: process and improve the AST if the language specification allows it (e.g. removing dead code, reorder operations, other optimizations)

Converting the AST to some form that a machine understands.

There only two real differences between the two.

In general, a program with multiple compilation units requires linking when compiling to machine code and generally does not with byte code. One could split hairs about whether linking is part of compiling in the context of this question. If so, byte code compilation would be slightly simpler. However, the complexity of linking is made up for at run-time when many linking concerns are handled by the VM (see my note below).

Byte code compilers tend not to optimize as much because the VM can do this better on the fly (JIT compilers are a fairly standard addition to VMs nowadays).

From this I conclude that byte code compilers can omit the complexity of most optimizations and all of linking, deferring both of these to the VM runtime. Byte code compilers are simpler in practice because they shovel many complexities onto the VM that machine code compilers take on themselves.

1 Not counting esoteric languages

Title: Compilation to bytecode vs machine code


答:
Guns dont kill people, people kill
  people.

In the same way, dev-tools are not evil, the things programmers do with them could be.

Title: Is anything in programming truly evil?


问:
MVVM: Should the VM be a value type?
I have been recently strongly influenced by two lectures: Gary Bernhardt's "Boundaries" (https://www.destroyallsoftware.com/talks/boundaries) and Andy Matuschak's "Controlling Complexity" (https://realm.io/news/andy-matuschak-controlling-complexity/)

I have also been learning about, and working with, the MVVM paradigm which leads to my question. Should the ViewModel be an immutable/value-type? Sometimes I think yes, others no.

I'm struck by the notion that the ViewModel is a link between the imperative shell and the functional core which I think is what is confusing me. Should the link between these two be imperative or functional in nature?

答:
The main purpose of a view model object is to provide a layer of abstraction between the View and the Model, so that you don't have to write code-behind spaghetti.  By putting the View logic into its own object, you decouple it from the actual UI surface and render its logic testable.

What would be the point of an immutable view model object?

Consider what you are getting with immutability: thread safety and the ability to compute an idempotent result from a function composition that is easier to reason about than a mutable object being operated on by several agents.

Are any of these conditions present in a View Model object?  No.

UI's are mutable by nature; you're not going to give people one chance, and one chance only, to enter data into a text box, are you?

Further, it is the mutable nature of the real world that requires purely functional languages to interact with the real world through mechanisms like monads.

Title: MVVM: Should the VM be a value type?


问:
How to write a test to cover a bugfix of a segfault
There was a bug that I recently fixed that was causing a segmentation fault (due to an out-of-bounds access).  The maintainer of the project is asking me to write a unit test to cover the bugfix.

How can I do this?  The bug exhibited undefined behavior, so even if my test passed, it's not proof of anything.  Should I use a loop to test it 100 times to make the test more likely to catch a regression?

答: Write a test that reliably reproduces the segfault in the original code first.  You should be able to duplicate the segfault by writing a test that causes the out of bound access that you fixed.  You can use the same test to demonstrate that the out-of-bound access no longer occurs in the new code.</p>


答:
In practice, most JVM today are very complex software, doing JIT compilation (so the bytecode is dynamically translated to machine code by the JVM).

So while the compilation from Java source code (or Clojure source code) to JVM byte code is indeed simpler, the JVM itself is doing complex translation to machine code.

The fact that this JIT translation inside the JVM is dynamic enables the JVM to focus on the most relevant parts of the bytecode. Practically speaking, most JVM optimize more the hottest parts (e.g. the most called methods, or the most executed basic blocks) of the JVM bytecode.

I'm not sure the the combined complexity of JVM + Java to bytecode compiler is significantly less than the complexity of ahead-of-time compilers.

Notice also that most traditional compilers (like GCC or Clang/LLVM) are transforming the input C (or C++, or Ada, ...) source code into an internal representation (Gimple for GCC, LLVM for Clang) which is quite similar to some bytecode. Then they are transforming that internal representations (first optimizing it into itself, i.e. most GCC optimizations passes are taking Gimple as input and producing Gimple as output; later emitting assembler or machine code from it) to object code.

BTW, with recent GCC (notably libgccjit) and LLVM infrastructure, you could use them to compile some other (or your own) language into their internal Gimple or LLVM representations, then profit from the many optimization abilities of the middle-end & back-end parts of these compilers.

Title: Compilation to bytecode vs machine code


答:
(1)

There is a concept of a "death test", in which a failing piece of code would cause a process termination.

In order to execute such death test, the test harness need to start a separate process which will execute the piece of code. The termination condition is then taken as the pass or fail criteria.

Obviously, not every unit testing framework supports this kind of tests.

(2)

Some C++ compilers provide switches that will insert additional checks into the generated code.

Examples of what these switches will do:

Ensure that when the function call returns, its return address has the same value (on the stack) as when the function call was just entered.

Ensure that dynamically allocated memory buffers were not being overwritten before its start or after its end.

(3)

Finally there are also code coverage and instrumentation tools such as valgrind.

If there exists some data patterns that will reliably causes a crash (but just that you don't know which one), fuzzing can be a very effective strategy for discovering such crash-causing data patterns. E.g. afl-fuzz.

If using additional tools is out-of-question, perhaps you can modify the code yourself to make it more "testable". An example is to replace array accesses with a C++ operator overload that performs array index bounds check. The details depend on the type of code being questioned.

Title: How to write a test to cover a bugfix of a segfault

Body:
There was a bug that I recently fixed that was causing a segmentation fault (due to an out-of-bounds access).  The maintainer of the project is asking me to write a unit test to cover the bugfix.

How can I do this?  The bug exhibited undefined behavior, so even if my test passed, it's not proof of anything.  Should I use a loop to test it 100 times to make the test more likely to catch a regression?


答:
The most pragmatic approach is IMHO by not blindly sticking to the model of "not changing the project's code under any circumstances."  So my suggestion is: make the code testable first - change the project's code slightly to make sure the out-of-bounds access leads to a reproducible and catchable error. Note that making code testable is very often a prerequisition for any kind of test automation.

That modification might be some kind of out-of-bounds assertion, using the kind of error-signaling your team normally uses inside your project (an error code, throwing an exception, calling a signal, or whatelse you prefer), but it should allow your automatic test to detect the error condition. Note further that this change is not the same "fixing the bug" - the bugfix should probably lead to code which doesn't create that out-of-bounds condition any more.

Then you should apply that change to the original code before the bug fix was applied (if you are lucky, your VCS system will help you to revert the order in which the changes are applied). Finally you can do exactly what Robert Harvey wrote - write a test which causes the error to appear, and run the test after you made the code testable, once before and once after the bugfix.


问:
Find all circles that cover one point
I'm not sure if I've been searching using the wrong keywords, but I've tried so many different ways of wording this and I can't find a relevant answer.

Basically, given a set of circles defined by their centers and radii and a point (x, y), I want to find all circles whose radii cover that particular point.

For example, say I have a website that lists a bunch of delivery restaurants that deliver only as far as a certain radius from their restaurant. I live at (x, y) and I want to run a query in my database that finds all the restaurants that deliver food to my place, so even if a restaurant is in Tokyo and if it claims to deliver within a radius of one light year, it should show up in a Californian's search.

The naive way is just to loop through all restraints in the database and compare the distance and the radius. How is this any different in terms of efficiency from a query that searches for all restaurants lying within a defined circle (typical Yelp problem)?

答:
You want to find things in a two-dimensional space easily. That is similar to the more common problem of finding things in a one-dimensional space; the solution there is to sort your data and then find things in it in O(log n) time via binary search.

You can't do exactly the same thing for two-dimensional data because the ordering is not the same for the two dimensions (a point that is quite small by one dimension might be very large by the other). But there are many generalizations of sorting/indexing that will nevertheless save you a lot of time in practice. The question has already been asked on stackoverflow, here.

Title: Find all circles that cover one point


答:
There is no true evil in programming.

<rant>

The reason so many people think that there are evil things is that it is pounded into their heads when they first take their programming classes. "Don't use goto! Always normalize your databases! Never, ever use multiple inheritance!" These are hammered in because these "evil" practices are so easily abused, not because they are inherently bad. There are so few uses of them that you can get away with saying "never" at first. What is truly evil is saying, "There is no reason to consider anything that is not a 'best practice'", because there is always a place where that very way is perfect.

</rant>

Title: Is anything in programming truly evil?


问:
Accidentally including unrelated changes in commits
My personal approach to a git commit is that every commit should include a unit of change, in its completness.

When I develop, I usually focus on such units. But sometimes, my attention strays someplace else and I work for a while on a different unit. This is probably not optimal, but I have learned to commit carefully (git add --interactive is a good friend of mine).

However, it could happen that I forget to selectively stage my changes and instead commit the whole file, believing that all the changes I see in the diff are indeed related to the same unit, even though there might be a change or two completely unrelated.

Then I git push.

Is this dangerous? Should I make effort to amend the commit so that it only includes the intended changes? My primary concern is that whoever else looks at the history will see the change and will probably scratch their heads for several minutes before realising it is most likely a mistake. Worse still, I can imagine that the change will even look related and the programmer might not recognise the error.

The problem is, since I have already pushed, I cannot safely rewrite the server's history, so I would probably have to first revert the commit, split it properly and commit again. Alternatively, I could just amend the commit with a better commit message, but I would have to be really really fast since it also requires rewriting history. As a last resort, I might simply commit the unit I was working on as next, leaving a note that there is a related change in previous commit (but this feels wrong).

I understand that in a multi-developer setups with proper code-review workflow this would likely not happen. I also understand that if I am the sole developer on a project, then rewriting history is the best solution for this.

答: It seems you have one local repository on your computer, and one repository shared with your coworkers on a server. Why do you have only one repository on your local computer? I usually have at least five, so I can work on one thing in one repository, fix a bug in another without touching the first repo, which might be in an incomplete state, and so on. </p>


答:
I was hoping there would be some kind of database optimization

Databases with spatial / geospatial extensions allow to store spatial objects and fast query operations like "is point in certain area", supported by so-called spatial indexes. The exact set of features as well as the syntax differs from DBMS to DBMS, but I do not know of a database which supports circle objects of different radius directly. But if your spatial database supports polygons (which is pretty standard), you can utilize this for your problem:

for each circle, store (additionally to center and radius) a polygon which encloses the circle (for lots of practical purposes, the  enclosing square is good enough).

use a spatial query for getting all circles where your given point (x,y) is contained in the related square. If you have many circles in total in your database, this could reduce the number of circles for a the point (x,y) to a much smaller amount

for the (hopefully small) result set, you test the "inside circle" condition manually by looping through the circles

In fact, you have to check if you benefit from this optimization in combination with your real data, and if the additional overhead of storing the enclosing polygons is really worth the hassle.

Title: Find all circles that cover one point

Body:
I'm not sure if I've been searching using the wrong keywords, but I've tried so many different ways of wording this and I can't find a relevant answer.

Basically, given a set of circles defined by their centers and radii and a point (x, y), I want to find all circles whose radii cover that particular point.

For example, say I have a website that lists a bunch of delivery restaurants that deliver only as far as a certain radius from their restaurant. I live at (x, y) and I want to run a query in my database that finds all the restaurants that deliver food to my place, so even if a restaurant is in Tokyo and if it claims to deliver within a radius of one light year, it should show up in a Californian's search.

The naive way is just to loop through all restraints in the database and compare the distance and the radius. How is this any different in terms of efficiency from a query that searches for all restaurants lying within a defined circle (typical Yelp problem)?


问:
Why should PHP developer use/learn VI editor?
Why should PHP developer use/learn VI editor ?

I mean there are 10 most amazing editors like PHPStorm, Netbeans which increases developers productivity.

Lets just consider PHPStorm. I never got amazed by editor like PHPStorm.

It has 1000s of features. Right from syntax hints, showing weak errors, warnings, notices etc.

When we compare number of features provided by VI Editor & those provided by editors like PHPStorm, we see it like 10 vs 1000 features.

My question is : Why should I learn to use Vi editor?

P.S. I am intermediate linux(Ubuntu) user.

Edit : Who told me to learn VI ? => Normally its required skill in Job Listing for PHP developer

Thanks.

答:
One possible reason is that you might need to edit PHP files from remote and it is much faster to access the server via SSH than remote desktop.

However, protocols such as SSH only give you access to the command (textual) interface of the server, i.e. the Terminal/Command prompt. Editors such as Netbeans require a graphical interface, yes you can access the server via remote desktop but anybody who has done it knows it is painfully slow and unproductive.

VI/VIM is a text-based editor, it does not require a graphical interface, which is preinstalled on most Unix/Linus platforms, and can run in a Terminal, thus it is especially convenient for editing files from remote when you only have access to the command interface of the server. Another common use for VI/VIM is to edit system administration files which require root privileges (I'm referring to Unix/Linux platforms) since VI/VIM can easily be run with the "sudo" command.


答: Databases has special index type for such kind of searches based on Minimum Bounding Boxes, called r-tree. Let's assume that we have 1M places defined by x/y in our database and we want to find all points in radius from our position we first need to build MBR containing search circle (center point in this same place and edges 2r), search data and in next step throw away results placed in MBR corners using simple formula x*x+y*y < r*r. R-tree aka range tree has also many of in-memory implementations for different languages. If you want to solve geographical problem it would be a little bit more complex as we have meridian, date change line and more complicated distance calculations (great circle).

Title: Find all circles that cover one point


问:
Using a one-shot class to store not-quite-global variables
I sometimes find myself writing classes (in Python, in my case) that are used like this:

```<code>MyClass(some_args).go()
</code>```

In other words, there's only one method in the class that any external code would call, and it will only ever get called once. There might be a return value from go() but often there isn't, and when there isn't, I could even call go from the class's __init__.

So why even bother with the class, instead of just writing go() as a standalone function? Because what goes on inside go is complicated. There may be several levels of nested function calls, and there are certain pieces of information that are needed in different spots. If I try to write all this without a class, I end up with a many of the functions returning multiple values. Sometimes the argument lists also get uncomfortably long. If I wrap everything up inside MyClass, then I can put all this information in member variables of the MyClass instance. These become not-quite-global variables, and they're generally stuff that feels like it make sense to store in a class.

Does this practice have a name? Is it a pattern, or an anti-pattern? And if the latter, how should I structure my code instead?

答: I do not think this practice has a special name, I would call it "encapsulation", "creating an abstraction by utilizing a class", "class design", or simply "OO programming". And it is definitely not an anti-pattern.</p>