答:
In a Microservices architecture, each one is absolutely independent of the others and it must hide the details of the internal implementation.

If you share the model you are coupling microservices and lose one of the greatest advantages in which each team can develop its microservice without restrictions and the need of knowing how evolve others microservices. Remember that you can even use different languages in each one, this would be difficult if you start to couple microservices.

If they are too related maybe they are really one like @soru says.

Related questions:

Why is it so bad to read data from a database “owned” by a different microservice

How do you handle shared concepts in a microservice architecture?

Title: Shared domain model between different microservices

Body:
Imagine a scenario of two different microservices. One to handle Authentication within the service, the other one takes care of User Management. They both have a concept of a User, and will talk about Users through calls to each other.

Where would the Domain model of a "User" belong though? Would they both have a different representation of what a User is on the level of the database? What about when we have a UserDTO to be used in API calls, would they both have one for their respective API's?

What is the general accepted solution for this kind of architectural issue?


问:
Does it make sense to use "ys" instead of "ies" in identifiers to ease find-and-replace functionality?
Although grammatically incorrect, when writing identifiers for functions, variables etc. does it make sense to simply append an "s" to plurals of words ending in Y? My reason for this would be that if you need to find-and-replace, for example, replacing "company" with "vendor", "company" would match both singular and plural forms ("company and "companys"), whereas if the plural was spelled correctly, you would have to do two separate searches.

答:
Any such search and replace should be performed with care and each change manually checked to eg avoid "accompany" in a comment becoming "acvendor" with your company/vendor change. As such, two separate searches for "company" and "companies" should not create a significant overhead compared with the time spent inspecting and approving each change.

So misspelling words to achieve only one search offers the negatives of looking bad and being more difficult to read than it need be, without offering any obvious benefit.

ContentLicense: CC BY-SA 3.0


问:
Is throwing new RuntimeExceptions in unreachable code a bad style?
I was assigned to maintain an application written some time ago by more skilled developers. I came across this piece of code:

```<code>public Configuration retrieveUserMailConfiguration(Long id) throws MailException {
        try {
            return translate(mailManagementService.retrieveUserMailConfiguration(id));
        } catch (Exception e) {
            rethrow(e);
        }
        throw new RuntimeException("cannot reach here");
    }
</code>```

I'm curious if throwing RuntimeException("cannot reach here") is justified. I'm probably missing something obvious knowing that this piece of code comes from more seasoned colleague.

EDIT:
Here is rethrow body that some answers referred to. I deemed it not important in this question.

```<code>private void rethrow(Exception e) throws MailException {
        if (e instanceof InvalidDataException) {
            InvalidDataException ex = (InvalidDataException) e;
            rethrow(ex);
        }
        if (e instanceof EntityAlreadyExistsException) {
            EntityAlreadyExistsException ex = (EntityAlreadyExistsException) e;
            rethrow(ex);
        }
        if (e instanceof EntityNotFoundException) {
            EntityNotFoundException ex = (EntityNotFoundException) e;
            rethrow(ex);
        }
        if (e instanceof NoPermissionException) {
            NoPermissionException ex = (NoPermissionException) e;
            rethrow(ex);
        }
        if (e instanceof ServiceUnavailableException) {
            ServiceUnavailableException ex = (ServiceUnavailableException) e;
            rethrow(ex);
        }
        LOG.error("internal error, original exception", e);
        throw new MailUnexpectedException();
    }

private void rethrow(ServiceUnavailableException e) throws
            MailServiceUnavailableException {
        throw new MailServiceUnavailableException();
    }

private void rethrow(NoPermissionException e) throws PersonNotAuthorizedException {
    throw new PersonNotAuthorizedException();
}

private void rethrow(InvalidDataException e) throws
        MailInvalidIdException, MailLoginNotAvailableException,
        MailInvalidLoginException, MailInvalidPasswordException,
        MailInvalidEmailException {
    switch (e.getDetail()) {
        case ID_INVALID:
            throw new MailInvalidIdException();
        case LOGIN_INVALID:
            throw new MailInvalidLoginException();
        case LOGIN_NOT_ALLOWED:
            throw new MailLoginNotAvailableException();
        case PASSWORD_INVALID:
            throw new MailInvalidPasswordException();
        case EMAIL_INVALID:
            throw new MailInvalidEmailException();
    }
}

private void rethrow(EntityAlreadyExistsException e)
        throws MailLoginNotAvailableException, MailEmailAddressAlreadyForwardedToException {
    switch (e.getDetail()) {
        case LOGIN_ALREADY_TAKEN:
            throw new MailLoginNotAvailableException();
        case EMAIL_ADDRESS_ALREADY_FORWARDED_TO:
            throw new MailEmailAddressAlreadyForwardedToException();
    }
}

private void rethrow(EntityNotFoundException e) throws
        MailAccountNotCreatedException,
        MailAliasNotCreatedException {
    switch (e.getDetail()) {
        case ACCOUNT_NOT_FOUND:
            throw new MailAccountNotCreatedException();
        case ALIAS_NOT_FOUND:
            throw new MailAliasNotCreatedException();
    }
}
</code>```

答:
The throw was probably added to get around the "method must return a value" error that would otherwise occur - the Java data flow analyser is smart enough to understand that no return is necessary after a throw, but not after your custom rethrow() method, and there is no @NoReturn annotation that you could use to fix this.

Nevertheless, creating a new Exception in unreachable code seems superfluous. I would simply write return null, knowing that it does, in fact, never happen.


答:
I don't know if there's a convention.

Anyhow, another trick would be to do like so:

```<code>private <T> T rethrow(Exception exception) {
    // or whatever it actually does
    Log.e("Ouch! " + exception.getMessage());
    throw new CustomWrapperException(exception);
}
</code>```

Allowing for this:

```<code>try {
     return translate(mailManagementService.retrieveUserMailConfiguration(id));
} catch (Exception e) {
     return rethrow(e);
}
</code>```

And no artificial RuntimeException is needed anymore. Even though rethrow never actually returns any value, it's good enough for the compiler now.

It does return a value in theory (method signature), and then it's exempt from actually doing so as it throws an exception instead.

Yeah, it might look weird, but then again - throwing a phantom RuntimeException, or returning nulls that'll never be seen in this world - that's not exactly a thing of beauty either.

Striving for readability, you could rename rethrow and have something like:

```<code>} catch (Exception e) {
     return nothingJustRethrow(e);
}
</code>```

Title: Is throwing new RuntimeExceptions in unreachable code a bad style?

Body:
I was assigned to maintain an application written some time ago by more skilled developers. I came across this piece of code:

```<code>public Configuration retrieveUserMailConfiguration(Long id) throws MailException {
        try {
            return translate(mailManagementService.retrieveUserMailConfiguration(id));
        } catch (Exception e) {
            rethrow(e);
        }
        throw new RuntimeException("cannot reach here");
    }
</code>```

I'm curious if throwing RuntimeException("cannot reach here") is justified. I'm probably missing something obvious knowing that this piece of code comes from more seasoned colleague.

EDIT:
Here is rethrow body that some answers referred to. I deemed it not important in this question.

```<code>private void rethrow(Exception e) throws MailException {
        if (e instanceof InvalidDataException) {
            InvalidDataException ex = (InvalidDataException) e;
            rethrow(ex);
        }
        if (e instanceof EntityAlreadyExistsException) {
            EntityAlreadyExistsException ex = (EntityAlreadyExistsException) e;
            rethrow(ex);
        }
        if (e instanceof EntityNotFoundException) {
            EntityNotFoundException ex = (EntityNotFoundException) e;
            rethrow(ex);
        }
        if (e instanceof NoPermissionException) {
            NoPermissionException ex = (NoPermissionException) e;
            rethrow(ex);
        }
        if (e instanceof ServiceUnavailableException) {
            ServiceUnavailableException ex = (ServiceUnavailableException) e;
            rethrow(ex);
        }
        LOG.error("internal error, original exception", e);
        throw new MailUnexpectedException();
    }

private void rethrow(ServiceUnavailableException e) throws
            MailServiceUnavailableException {
        throw new MailServiceUnavailableException();
    }

private void rethrow(NoPermissionException e) throws PersonNotAuthorizedException {
    throw new PersonNotAuthorizedException();
}

private void rethrow(InvalidDataException e) throws
        MailInvalidIdException, MailLoginNotAvailableException,
        MailInvalidLoginException, MailInvalidPasswordException,
        MailInvalidEmailException {
    switch (e.getDetail()) {
        case ID_INVALID:
            throw new MailInvalidIdException();
        case LOGIN_INVALID:
            throw new MailInvalidLoginException();
        case LOGIN_NOT_ALLOWED:
            throw new MailLoginNotAvailableException();
        case PASSWORD_INVALID:
            throw new MailInvalidPasswordException();
        case EMAIL_INVALID:
            throw new MailInvalidEmailException();
    }
}

private void rethrow(EntityAlreadyExistsException e)
        throws MailLoginNotAvailableException, MailEmailAddressAlreadyForwardedToException {
    switch (e.getDetail()) {
        case LOGIN_ALREADY_TAKEN:
            throw new MailLoginNotAvailableException();
        case EMAIL_ADDRESS_ALREADY_FORWARDED_TO:
            throw new MailEmailAddressAlreadyForwardedToException();
    }
}

private void rethrow(EntityNotFoundException e) throws
        MailAccountNotCreatedException,
        MailAliasNotCreatedException {
    switch (e.getDetail()) {
        case ACCOUNT_NOT_FOUND:
            throw new MailAccountNotCreatedException();
        case ALIAS_NOT_FOUND:
            throw new MailAliasNotCreatedException();
    }
}
</code>```

Body:
I don't know if there's a convention.

Anyhow, another trick would be to do like so:

private <T> T rethrow(Exception exception) {
    // or whatever it actually does
    Log.e("Ouch! " + exception.getMessage());
    throw new CustomWrapperException(exception);
}

Allowing for this:

try {
     return translate(mailManagementService.retrieveUserMailConfiguration(id));
} catch (Exception e) {
     return rethrow(e);
}

And no artificial RuntimeException is needed anymore. Even though rethrow never actually returns any value, it's good enough for the compiler now.

It does return a value in theory (method signature), and then it's exempt from actually doing so as it throws an exception instead.

Yeah, it might look weird, but then again - throwing a phantom RuntimeException, or returning nulls that'll never be seen in this world - that's not exactly a thing of beauty either.

Striving for readability, you could rename rethrow and have something like:

} catch (Exception e) {
     return nothingJustRethrow(e);
}


问:
Dependency Management in the real world?
Most of the examples i've see when watching anything on dependency management hit what i consider to be the holy grail in that the only dependencies on classes are interfaces that the IOC container can inject in. Of course most of the examples have to be trivial because of time constraints the presenter is under. Thats great for the client because they don't have to worry about hydrating classes but is that very real world? For example i'm working on a class has a variety of calculations. Here is the constructor:

```<code>public OsEarnDetail(IOsMacRateRepository macRates,IRate rate, OsEarnDetailPoco data)
    {
        _macRates = macRates;
        _rate = rate;
        _data = data;
    }
</code>```

As you can see, i have data structure which is going to prevent any IOC container from being able to hydrate the class automatically. Say this class has a complex function called CalcFoo(). I not only have to calculate this value when a record is being retrieved/saved from the database. The results of this calculation need to be displayed to the user as the type a new entry (even before it get save to the database) and also recalculated if a user is changing any of the core data (again before it has been saved to the database).

Am i confused in any way or is there something wrong with the way in constructing my classes? I would think it would be common to have scenarios where you must run complex business logic even before it has been saved to the database and therefore you must hydrate your business objects with a set of data which would prevent your IOC container for being able to fully hydrate your dependencies.

答:
In this case, CalcFoo() should take in an OsEarnDetailPoco.  The method signature then becomes CalcFoo(OsEarnedDetailPoco data).

Services are typically injected in a DI architecture.  Data is usually passed around through method calls.


答:
This rethrow(e); function violates the principle which says that under normal circumstances, a function will return, while under exceptional circumstances, a function will throw an exception.  This function violates this principle by throwing an exception under normal circumstances.  That's the source of all of the confusion.

The compiler assumes that this function will return under normal circumstances, so as far as the compiler can tell, execution may reach the end of the retrieveUserMailConfiguration function, at which point it is an error not to have a return statement.  The RuntimeException thrown there is supposed to alleviate this concern of the compiler, but it is a rather clunky way of doing it. Another way of preventing the function must return a value error is to add a return null; //to keep the compiler happy statement, but that's equally clunky in my opinion.

So, personally, I would replace this:

```<code>rethrow(e);
</code>```

with this:

```<code>report(e);
throw e;
</code>```

or, better yet, (as coredump suggested,) with this:

```<code>throw reportAndTransform(e);
</code>```

Thus, the flow of control would be made obvious to the compiler, so your final throw new RuntimeException("cannot reach here"); would become not only redundant, but actually not even compilable, since it would be flagged by the compiler as unreachable code.

That's the most elegant and actually also simplest way of getting out of this ugly situation.

Body:
This rethrow(e); function violates the principle which says that under normal circumstances, a function will return, while under exceptional circumstances, a function will throw an exception.  This function violates this principle by throwing an exception under normal circumstances.  That's the source of all of the confusion.

The compiler assumes that this function will return under normal circumstances, so as far as the compiler can tell, execution may reach the end of the retrieveUserMailConfiguration function, at which point it is an error not to have a return statement.  The RuntimeException thrown there is supposed to alleviate this concern of the compiler, but it is a rather clunky way of doing it. Another way of preventing the function must return a value error is to add a return null; //to keep the compiler happy statement, but that's equally clunky in my opinion.

So, personally, I would replace this:

rethrow(e);

with this:

report(e);
throw e;

or, better yet, (as coredump suggested,) with this:

throw reportAndTransform(e);

Thus, the flow of control would be made obvious to the compiler, so your final throw new RuntimeException("cannot reach here"); would become not only redundant, but actually not even compilable, since it would be flagged by the compiler as unreachable code.

That's the most elegant and actually also simplest way of getting out of this ugly situation.


问:
Web framework in pure SQL
I heard that SQL is Turing complete language (for example: https://stackoverflow.com/a/7580013/2604170) I am just curious if would be possible to create independent web framework like Ruby on rails or Flask (Python) in pure SQL (SQL would replace python or ruby or java for example)

It's just idea, but I think it would be really interesting if something like this could work.

I apologize, if it's stupid question.

Thanks in advance.

答: No, because you need at least basic IO capabilities to be able to serve up web content. Assuming you finesse that by using something else to put in front of your database server then, yes, technically that would be possible. It would just be horrible.</p>

Title: Web framework in pure SQL


问:
Incorporating functions into a Shunting-Yard algorithm implementation
tl;dr What would be a simple way of incorporating functions into a Shunting-Yard algorithm implementation?

If only expressions like function(arg1, arg2, arg3) were allowed (where function is some builtin function), then it would be really easy, since I could just treat function like an operator. But consider a case where the user defines their own function like f = function, then calls f(arg1, arg2, arg3). In this case I would need a strongly-typed AST to detect at compile time what f's type is in order to see that the proceeding tokens ((arg1, arg2, arg3)) are actually a function call, and not just a construction of a tuple.

Even worse, consider (f)() where f is a user-defined nullary function. Then when I get to f, even if I know that it's a function, the next token will be ), which is not the start of a valid function call. What about (l[i])(), where l is a list of functions?

At the most general level, I understand grammatically that when we have a statement like [expression], "(", [expression], ")", then we know that we're calling a function. However, I'm not quite sure how to check this without implementation an AST (which, for simplicity's sake, I would rather not do).

I could store a list of all operator and "bracket" tokens, and then when I reach the "(" in a supposed function call I just check whether the last non-bracket token was an operator. If it was an operator then the "(" represents a subexpression, like in 5 * (3 - 8). If it wasn't an operator, then the "(" represents a function call. However, this method feels easily broken. For example, what if there where some operator $ that was "unary left-associative", so that (expression $)(args) was valid? Then the algorithm would fail unless I had special checking for $. What if there was a comment between the function and the function call, like function \* comment *\ (args)? Or even worse, something like

```<code>function \\ lol the last token in this comment is an operator +
    (args)
</code>```

These would require implementing handlers a lot of special cases, and I'm wondering if there's a better way of doing it.

答:
It's an opening bracket which follows directly after a identifier. So when you meet a open bracket you check whether the last token you parsed was a identifier or a operator. If it was an operator then it's a just a subexpression if not then it's part of a function call.

Comments should be dealt with before the you parse the token stream.

This turns you last bit of code into identifier comment openBracket identifier closeBracket where you can ignore the comment token when building the AST or doing the shunting yard.


答:
First, thanks for udpating your question and showing us what rethrow does. So, in fact, what it does is converting exceptions with properties into more fined-grained classes of exceptions. More on this later.

Since I did not really answer the main question originally, here it goes: yes, it is generally bad style to throw runtime exceptions in unreachable code; you'd better use assertions, or even better, avoid the problem. As already pointed out, the compiler here cannot be sure that the code never walks out of the try/catch block. You can refactor your code by taking advantage that...

Errors are values

(Unsurprisingly, it is well-known in go)

Let's use a simpler example, the one I used before your edit: so imagine that you are logging something and building a wrapper exception like in Konrad's answer. Let's call it logAndWrap.

Instead of throwing the exception as a side-effect of logAndWrap, you could let it do its work as a side-effect and make it return an exception (at least, the one given in input). You don't need to use generics, just basic functions:

```<code>private Exception logAndWrap(Exception exception) {
    // or whatever it actually does
    Log.e("Ouch! " + exception.getMessage());
    return new CustomWrapperException(exception);
}
</code>```

Then, you throw explicitely, and your compiler is happy:

```<code>try {
     return translate(mailManagementService.retrieveUserMailConfiguration(id));
} catch (Exception e) {
     throw logAndWrap(e);
}
</code>```

What if you forget to throw?

As explained in Joe23's comment, a defensive programming way to ensure that the exception is always thrown would consists in explicitely doing a throw new CustomWrapperException(exception) at the end of logAndWrap, as it is done by Guava.Throwables. That way, you know that the exception will be thrown, and your type analyzer is happy. However, your custom exceptions need to be unchecked exceptions, which is not always possible. Also, I'd rate the risk of a developper missing to write throw to be very low: the developer must forget it and the surrounding method should not return anything, otherwise the compiler would detect a missing return. This is an interesting way to fight the type system, and it works, though.

Rethrow

The actual rethrow can be written as a function too, but I have problems with its current implementation:

There are many useless casts like Casts are in fact required  (see comments):

```<code>if (e instanceof ServiceUnavailableException) {
    ServiceUnavailableException ex = (ServiceUnavailableException) e;
    rethrow(ex);
}
</code>```

When throwing/returning new exceptions, the old one is discarded; in the following code, a MailLoginNotAvailableException does not allow me to know which login is not available, which is inconvenient; moreover, stacktraces will be incomplete:

```<code>private void rethrow(EntityAlreadyExistsException e)
    throws MailLoginNotAvailableException, MailEmailAddressAlreadyForwardedToException {
    switch (e.getDetail()) {
        case LOGIN_ALREADY_TAKEN:
            throw new MailLoginNotAvailableException();
        case EMAIL_ADDRESS_ALREADY_FORWARDED_TO:
            throw new MailEmailAddressAlreadyForwardedToException();
    }
}
</code>```

Why doesn't the originating code throws those specialized exceptions in the first place? I suspect that rethrow is used as a compatibility layer between a (mailing) subsystem and busineess logic (maybe the intent is to hide implementation details like thrown exceptions by replacing them by custom exceptions). Even if I agree that it would be better to have catch-free code, as suggested in Pete Becker's answer, I don't think you'll have an opportunity to remove the catch and rethrow code here without major refactorings.

Body:
First, thanks for udpating your question and showing us what rethrow does. So, in fact, what it does is converting exceptions with properties into more fined-grained classes of exceptions. More on this later.

Since I did not really answer the main question originally, here it goes: yes, it is generally bad style to throw runtime exceptions in unreachable code; you'd better use assertions, or even better, avoid the problem. As already pointed out, the compiler here cannot be sure that the code never walks out of the try/catch block. You can refactor your code by taking advantage that...

Errors are values

(Unsurprisingly, it is well-known in go)

Let's use a simpler example, the one I used before your edit: so imagine that you are logging something and building a wrapper exception like in Konrad's answer. Let's call it logAndWrap.

Instead of throwing the exception as a side-effect of logAndWrap, you could let it do its work as a side-effect and make it return an exception (at least, the one given in input). You don't need to use generics, just basic functions:

private Exception logAndWrap(Exception exception) {
    // or whatever it actually does
    Log.e("Ouch! " + exception.getMessage());
    return new CustomWrapperException(exception);
}

Then, you throw explicitely, and your compiler is happy:

try {
     return translate(mailManagementService.retrieveUserMailConfiguration(id));
} catch (Exception e) {
     throw logAndWrap(e);
}

What if you forget to throw?

As explained in Joe23's comment, a defensive programming way to ensure that the exception is always thrown would consists in explicitely doing a throw new CustomWrapperException(exception) at the end of logAndWrap, as it is done by Guava.Throwables. That way, you know that the exception will be thrown, and your type analyzer is happy. However, your custom exceptions need to be unchecked exceptions, which is not always possible. Also, I'd rate the risk of a developper missing to write throw to be very low: the developer must forget it and the surrounding method should not return anything, otherwise the compiler would detect a missing return. This is an interesting way to fight the type system, and it works, though.

Rethrow

The actual rethrow can be written as a function too, but I have problems with its current implementation:

There are many useless casts like Casts are in fact required  (see comments):

if (e instanceof ServiceUnavailableException) {
    ServiceUnavailableException ex = (ServiceUnavailableException) e;
    rethrow(ex);
}

When throwing/returning new exceptions, the old one is discarded; in the following code, a MailLoginNotAvailableException does not allow me to know which login is not available, which is inconvenient; moreover, stacktraces will be incomplete:

private void rethrow(EntityAlreadyExistsException e)
    throws MailLoginNotAvailableException, MailEmailAddressAlreadyForwardedToException {
    switch (e.getDetail()) {
        case LOGIN_ALREADY_TAKEN:
            throw new MailLoginNotAvailableException();
        case EMAIL_ADDRESS_ALREADY_FORWARDED_TO:
            throw new MailEmailAddressAlreadyForwardedToException();
    }
}

Why doesn't the originating code throws those specialized exceptions in the first place? I suspect that rethrow is used as a compatibility layer between a (mailing) subsystem and busineess logic (maybe the intent is to hide implementation details like thrown exceptions by replacing them by custom exceptions). Even if I agree that it would be better to have catch-free code, as suggested in Pete Becker's answer, I don't think you'll have an opportunity to remove the catch and rethrow code here without major refactorings.


答:
Yes! Yes! Yes!  It makes perfect sense to do that.  And I have been doing it for years.

Disclosure 1: English is not my native language.

Disclosure 2: My knowledge of English grammar is considerably better than that of the average native speaker.

Disclosure 3: When it comes to communicating with humans, I am a vehement grammar Nazi.

And now that these disclosures are out of the way, let me state that English grammar has no place in code.  You see, that's why it is called code and not prose.  It is supposed to have some resemblance to a language understood by humans, for the purpose of readability, but other than that, what we mostly need from code is not the qualities of prose; it is other, more technical qualities, like precision, unambiguity, and terseness.  That's why the C syntax of if( x != y ) y++; is much preferable to the IF X IS NOT EQUAL TO Y THEN ADD 1 TO Y END-IF. syntax of Cobol.  The alleged desirability of compilers that understand natural language is a fallacy, and don't take my word for it, see what ol'Edsger has to say about it: Edsger W. Dijkstra, On the foolishness of "natural language programming".

Another quality which is of importance is computability of identifiers.  The fact that a property called Color can always be read via a method called getColor() and written via a method called setColor() is of paramount importance.  These identifiers are computable from the name of the property, so you do not have to know them by heart. If a programmer was to choose a pair of methods called getColor() on one hand, but colorize() on the other hand, their colleagues would rightfully consider this sabotage.  That's how important identifier computability is.

Also, programming tools can be written (and plenty of them have in fact been written, for example, Hibernate) which can compute these names. Without identifier name computability you would have to use additional syntax (e.g. in Hibernate, extra annotations) to specify to each tool precisely how to create every single identifier name, or precisely which ad hoc name you have given to each entity.

So, identifier computability is important, while at the same time English grammar is irrelevant, (since we are not doing natural language programming,) so to be able to compute the name of a collection of entities by always appending "s" to the name of a single instance makes perfect sense, never mind the fact that it violates most people's (mine included) English language sensitivities.

And whether we like it or not, this is the trend of the future.  The native language of the majority of programmers on the planet is not English anymore, and the trend is to continue very strong in this direction.  (Also, I would not even be willing to bet money on the suggestion that English is the native language of the majority of programmers working in the USA right now.) These are people who, to a large extent, when trying to calculate the name of a collection from the name of a single instance of "company", will simply append an "s", and the form "companies" will not even cross their mind.  To a great and ever increasing percentage of programmers in the world, knowledge of the peculiarities of the English language does not add any value to their work, it only makes it slightly harder.

Title: Does it make sense to use "ys" instead of "ies" in identifiers to ease find-and-replace functionality?

Body: Although grammatically incorrect, when writing identifiers for functions, variables etc. does it make sense to simply append an "s" to plurals of words ending in Y? My reason for this would be that if you need to find-and-replace, for example, replacing "company" with "vendor", "company" would match both singular and plural forms ("company and "companys"), whereas if the plural was spelled correctly, you would have to do two separate searches.


答:
The

```<code>throw new RuntimeException("cannot reach here");
</code>```

statement makes it clear to a PERSON reading the code what is going on, so is a lot better then returning null for example.
It also make it easier to debug if the code is changed in an unexpected way.

However rethrow(e) just seems wrong!   So in your case I think refactoring the code is a better option.    See the other answers (I like coredump's best) for ways to sort your code out.

Body:
The

throw new RuntimeException("cannot reach here");

statement makes it clear to a PERSON reading the code what is going on, so is a lot better then returning null for example.
It also make it easier to debug if the code is changed in an unexpected way.

However rethrow(e) just seems wrong!   So in your case I think refactoring the code is a better option.    See the other answers (I like coredump's best) for ways to sort your code out.


答:
If you remove the try block completely then you don't need the rethrow or the throw. This code does exactly the same thing as the original:

```<code>public Configuration retrieveUserMailConfiguration(Long id) throws MailException {
    return translate(mailManagementService.retrieveUserMailConfiguration(id));
}
</code>```

Don't let the fact that it comes from more seasoned developers fool you. This is code rot, and it happens all the time. Just fix it.

EDIT: I mis-read rethrow(e) as simply re-throwing the exception e. If that rethrow method actually does something other than re-throw the exception, then getting rid of it does change the semantics of this method.

Body:
If you remove the try block completely then you don't need the rethrow or the throw. This code does exactly the same thing as the original:

public Configuration retrieveUserMailConfiguration(Long id) throws MailException {
    return translate(mailManagementService.retrieveUserMailConfiguration(id));
}

Don't let the fact that it comes from more seasoned developers fool you. This is code rot, and it happens all the time. Just fix it.

EDIT: I mis-read rethrow(e) as simply re-throwing the exception e. If that rethrow method actually does something other than re-throw the exception, then getting rid of it does change the semantics of this method.


答:
I use a two state, two stack model similar to the Shunting Yard algorithm.  The two states are the unary state and the binary state.  In each state, you handle tokens (or issue errors) and then either continue the same state or switch to the other state.

In the unary state, if you find an open paren, (, it is operator grouping, and, you stay in the unary state.  (In the unary state, an identifier is a variable reference you push it onto the operand stack, and switch to the binary state; a minus, -, is a unary negation, and you stay in unary state.)

In the binary state, if you find an open paren, it is a function invocation (and you switch to the unary state).  Differentiating between the two states also help you deal with unary and pre/post-fix operators.  (Here a minus, -, is a binary subtraction and you switch to unary state.)

ok, for the expression (*p[i++])(), p is a pointer to pointer to function, right?  So,

(Note that the empty parameter list expression should only be allowed when function calls are actually present; there are various ways and places for detecting the various possible errors.)

The actual tokens handled in unary state and in binary state are determined by the language you're trying to parse.  I allow separate code sections for the unary state and the binary state.  There seems to be no point in mixing them and then you don't need a state variable either (the code section just knows which one it is).

Title: Incorporating functions into a Shunting-Yard algorithm implementation

Body:
tl;dr What would be a simple way of incorporating functions into a Shunting-Yard algorithm implementation?

If only expressions like function(arg1, arg2, arg3) were allowed (where function is some builtin function), then it would be really easy, since I could just treat function like an operator. But consider a case where the user defines their own function like f = function, then calls f(arg1, arg2, arg3). In this case I would need a strongly-typed AST to detect at compile time what f's type is in order to see that the proceeding tokens ((arg1, arg2, arg3)) are actually a function call, and not just a construction of a tuple.

Even worse, consider (f)() where f is a user-defined nullary function. Then when I get to f, even if I know that it's a function, the next token will be ), which is not the start of a valid function call. What about (l[i])(), where l is a list of functions?

At the most general level, I understand grammatically that when we have a statement like [expression], "(", [expression], ")", then we know that we're calling a function. However, I'm not quite sure how to check this without implementation an AST (which, for simplicity's sake, I would rather not do).

I could store a list of all operator and "bracket" tokens, and then when I reach the "(" in a supposed function call I just check whether the last non-bracket token was an operator. If it was an operator then the "(" represents a subexpression, like in 5 * (3 - 8). If it wasn't an operator, then the "(" represents a function call. However, this method feels easily broken. For example, what if there where some operator $ that was "unary left-associative", so that (expression $)(args) was valid? Then the algorithm would fail unless I had special checking for $. What if there was a comment between the function and the function call, like function \* comment *\ (args)? Or even worse, something like

```<code>function \\ lol the last token in this comment is an operator +
    (args)
</code>```

These would require implementing handlers a lot of special cases, and I'm wondering if there's a better way of doing it.


问:
How to reuse domain model logic in services?
I am trying to avoid anemic domain models as it's said to be an anti-pattern. But doing so leaves my services to duplicate some of the logic.

```<code>class User
{
    public $status;

    public function ban()
    {
        $this->status = 'banned';
    }
}
</code>```

Now, a ban service allows to ban users by only having user's id, so there's no need to fetch the whole model.

```<code>class BanService()
{
    public function __construct(IUserRepo $userRepo)
    {
        $this->userRepo = $userRepo;
    }

    public function banUser($userId)
    {
        $this->userRepo->update($userId, ['status' => 'banned'])
    }
}
</code>```

What is the commonly used pattern to deal with this?

答:
I'd implement a BanCommand class, which takes care of this.  Domain models don't necessarily have to have state; sometimes they represent actions that take data and do something.  That's pretty normal OO too; objects are behavior + state, but sometimes the objects don't really need any state to do something useful.  That's why I always list behavior before state when I describe OO; the real thing is the behavior you're trying to model.  The state is just there to enable the behavior the user wants.

I don't see any issue just using this class directly either, just as you would any other domain model.  You could have a Ban method on User which delegates to the command, but this would just be for convenience (say you're already editing a user and you want to have a Ban button).  Whatever you end up doing will be driven by your exact use cases.


问:
Depend in the direction of stability: How do I know what is more stable?
According to the Stable Dependencies Principle, the dependency

should be in the direction of the stability

But:

if you don't know what types of changes are likely, it is best to wait and see what happens as the system evolves.

Now:

Say I'm designing a blog, I am tempted to think the stability ranking is:

Comment - less likely to change

Post

User - more likely to change (because it's bigger?)

If I let Comment depend on Post, then Comment will change more likely. But also vice-versa, if I let Post depend on Comment, Post will change more likely, correct?

This wants to be a general argument, every app has a hierarchy similar to users, a main object and children.

Where is my best bet for change? higher level classes or lower level? And why?

答:
I found some good help on this talk from Sandi Metz, one of my idols, Less the path to better design.

At 16:05 the Stable Dependencies Principle comes up in the context I am interested in, class design.  Her point is "you can't know", so embrace uncertainty.  It's a great talk.

So I went on and checked the churns of some of the apps I currently maintain and it seems the order is the one given in my question.

However, that might be the way we are used to manage direction, for good or bad.  Inverting the direction will likely produce the opposite effects.


问:
Java: difference between String a = null and String a = new String()
It's a pretty naive question to ask but I got this doubt while programming for Android. I use to initialize my new strings like String a=null, so in my code there remains a probability to get NullPointerException if I forget to initialize the variable before accessing it but what about the other case. Also which one should be used?

答:
In general you want to keep declaration and initialisation as close as possible to minimise exactly the type of problem you're talking about.

There is also the issue of redundant initialisation where the value null you're assigning is never used which is extra code that harms readability even if the redundant assignment is optimised away by the compiler.

Sometimes assigning some sort of default value is unavoidable, for example if you declare before a try catch, initialise inside and use it afterwards. For other types you can often find a more natural default value such as an empty list.


问:
Testing Scenarios More than Once
Is there an industry standard in how many times a scenario is tested before it is considered passed?  Is it common to test a given scenario using multiple different records?

Here is the issue:  A development project is now in the SIT phase and the developers' plan is to test each scenario once unless it fails.  There is an opinion that the scenario needs to be tested more than once before considered passed because, in the past, there were defects found during UAT for scenarios that passed in SIT.

答:
IMHO you are asking the wrong question. Does it really make a difference for your software's quality or the efficiency of your tests if there is an "industry standard" or not? There is no widely accepted standard, nevertheless what you should ask yourself is: "does adding  multiple different records for the same test scenario improve our process?"

My suggestion is to approach this from a pragmatic point of view. Test cases are good if they have a potential to reveal defects. If your current set of test cases has overlooked a defect which was found later, it is obviously a good idea to add one or more test cases to the pool which can reveal this defect (or even better: defects of the same type) to let this not happen again. If these test cases count as "the same scenario" or "a different scenario" is pretty much irrelevant for you and your team - if they are useful, add them, if they are only testing things already included in other test cases, omit them.

And do yourself a favor and stop thinking in terms of "lets do this because everyone else does it" - that is an organizational anti-pattern called cargo cult programming (it's description will fit for "testing" as well).

Title: Testing Scenarios More than Once


答:
First let's clarify something: You mention that after assigning null to the variable you could forget to initialize it, but by assigning null to it you are in effect initializing it.

```<code>public static void main (String args[]){
    String s;
    System.out.println(s); // compiler error variable may not be initialized
}
</code>```

vs

```<code>public static void main (String args[]){
    String s=null;
    System.out.println(s); // no compiler error
    System.out.println(s.equals("helo")); // but this will generate an exception
}
</code>```

So after you do String s=null; there's is no way that you could forget to initialize because you did initialize it.

That being clear, I would recommend you to use a "smart default". In your case perhaps the empty string "" would be a good default value if you want to avoid NullPointerException. In the other hand, sometimes it is desirable that the program produce an exception because it indicates something wrong happened under the hood that should not have happened.

Title: Java: difference between String a = null and String a = new String()

Body: It's a pretty naive question to ask but I got this doubt while programming for Android. I use to initialize my new strings like String a=null, so in my code there remains a probability to get NullPointerException if I forget to initialize the variable before accessing it but what about the other case. Also which one should be used?

Body:
First let's clarify something: You mention that after assigning null to the variable you could forget to initialize it, but by assigning null to it you are in effect initializing it.

public static void main (String args[]){
    String s;
    System.out.println(s); // compiler error variable may not be initialized
}

vs

public static void main (String args[]){
    String s=null;
    System.out.println(s); // no compiler error
    System.out.println(s.equals("helo")); // but this will generate an exception
}

So after you do String s=null; there's is no way that you could forget to initialize because you did initialize it.

That being clear, I would recommend you to use a "smart default". In your case perhaps the empty string "" would be a good default value if you want to avoid NullPointerException. In the other hand, sometimes it is desirable that the program produce an exception because it indicates something wrong happened under the hood that should not have happened.


问:
Is there a Haskell idiom for trying several functions and stop as soon as one succeeds?
In Haskell, I can use the type a -> Maybe b to model a function that either returns a value of type b, or returns nothing (it fails).

If I have types a1, ..., a(n+1) and functions f1, ..., fn, with fi :: ai -> Maybe a(i+1) for all i, 1 <= i <= n, I can chain the functions by using the >>= operator of the Maybe monad and write:

```<code>f1 x >>= f2 >>= f3 >>=... >>= fn
</code>```

The >>= operator ensures that each function is applied as long as its predecessor has returned a meaningful value. As soon as a function in the chain fails, the whole chain fails (returns Nothing) and further functions in the chain are not evaluated.

I have a somewhat similar pattern in which I want to try several functions on the same input, and return as soon as one function succeeds. If all functions fail (return Nothing), the whole computation should fail. More precisely, I have functions f1, ..., fn :: a -> Maybe b and I define the function

```<code>tryFunctions :: [a -> Maybe b] -> a -> Maybe b
tryFunctions []       _ = Nothing
tryFunctions (f : fs) x = case f x of
                            Nothing    -> tryFunctions fs x
                            r@(Just _) -> r
</code>```

In a sense this is dual to the Maybe monad in that a computation stops at the first success instead of at the first failure.

Of course, I can use the function I have written above but I was wondering if there is a better, well-established and idiomatic way of expressing this pattern in Haskell.

答:
Given a closed set (fixed number of elements) S with elements {a..z} and a binary operator *:

There is a single identity element i such that:

forall x in S: i * x = x = x * i

The operator is associative such that:

forall a, b, c in S: a * (b * c) = (a * b) * c

You have a monoid.

Now given any monoid you can define a binary function f as:

```<code>f(i, x) = x
f(x, _) = x
</code>```

What this means is that for the example of the Maybe monoid (Nothing is the identity element denoted above as i):

```<code>f(Nothing, Just 5) = Just 5
f(Just 5, Nothing) = Just 5
f(Just 5, Just 10) = Just 5
f(Nothing, f(Nothing, Just 5)) = Just 5
f(Nothing, f(Just 5, Nothing)) = Just 5
</code>```

Surprisingly, I can't find this precise function in the default libraries, which is likely due to my own inexperience. If anyone else can volunteer this, I would sincerely appreciate it.

Here's the implementation I deduced off hand from the above example:

```<code>(<||>) :: (Monoid a, Eq a) => a -> a -> a
x <||> y
     | x == mempty = y
     | True = x
</code>```

Example:

```<code>λ> [] <||> [1,2] <||> [3,4]
[1,2]
λ> Just "foo" <||> Nothing <||> Just "bar"
Just "foo"
λ> Nothing <||> Just "foo" <||> Just "bar"
Just "foo"
λ>
</code>```

Then if you want to use a list of functions as input...

```<code>tryFunctions x funcs = foldl1 (<||>) $ map ($ x) funcs
</code>```

example:

```<code>instance Monoid Bool where
         mempty = False
         mconcat = or
         mappend = (||)

λ> tryFunctions 8 [odd, even]
True
λ> tryFunctions 8 [odd, odd]
False
λ> tryFunctions 8 [odd, odd, even]
True
λ>
</code>```

Body:
Given a closed set (fixed number of elements) S with elements {a..z} and a binary operator *:

There is a single identity element i such that:

forall x in S: i * x = x = x * i

The operator is associative such that:

forall a, b, c in S: a * (b * c) = (a * b) * c

You have a monoid.

Now given any monoid you can define a binary function f as:

f(i, x) = x
f(x, _) = x

What this means is that for the example of the Maybe monoid (Nothing is the identity element denoted above as i):

f(Nothing, Just 5) = Just 5
f(Just 5, Nothing) = Just 5
f(Just 5, Just 10) = Just 5
f(Nothing, f(Nothing, Just 5)) = Just 5
f(Nothing, f(Just 5, Nothing)) = Just 5

Surprisingly, I can't find this precise function in the default libraries, which is likely due to my own inexperience. If anyone else can volunteer this, I would sincerely appreciate it.

Here's the implementation I deduced off hand from the above example:

(<||>) :: (Monoid a, Eq a) => a -> a -> a
x <||> y
     | x == mempty = y
     | True = x

Example:

λ> [] <||> [1,2] <||> [3,4]
[1,2]
λ> Just "foo" <||> Nothing <||> Just "bar"
Just "foo"
λ> Nothing <||> Just "foo" <||> Just "bar"
Just "foo"
λ>

Then if you want to use a list of functions as input...

tryFunctions x funcs = foldl1 (<||>) $ map ($ x) funcs

example:

instance Monoid Bool where
         mempty = False
         mconcat = or
         mappend = (||)

λ> tryFunctions 8 [odd, even]
True
λ> tryFunctions 8 [odd, odd]
False
λ> tryFunctions 8 [odd, odd, even]
True
λ>


答:
```<code>import Data.Monoid

tryFunctions :: a -> [a -> Maybe b] -> Maybe b
tryFunctions x = getFirst . mconcat . map (First . ($ x))
</code>```

Title: Is there a Haskell idiom for trying several functions and stop as soon as one succeeds?

Body:
In Haskell, I can use the type a -> Maybe b to model a function that either returns a value of type b, or returns nothing (it fails).

If I have types a1, ..., a(n+1) and functions f1, ..., fn, with fi :: ai -> Maybe a(i+1) for all i, 1 <= i <= n, I can chain the functions by using the >>= operator of the Maybe monad and write:

```<code>f1 x >>= f2 >>= f3 >>=... >>= fn
</code>```

The >>= operator ensures that each function is applied as long as its predecessor has returned a meaningful value. As soon as a function in the chain fails, the whole chain fails (returns Nothing) and further functions in the chain are not evaluated.

I have a somewhat similar pattern in which I want to try several functions on the same input, and return as soon as one function succeeds. If all functions fail (return Nothing), the whole computation should fail. More precisely, I have functions f1, ..., fn :: a -> Maybe b and I define the function

```<code>tryFunctions :: [a -> Maybe b] -> a -> Maybe b
tryFunctions []       _ = Nothing
tryFunctions (f : fs) x = case f x of
                            Nothing    -> tryFunctions fs x
                            r@(Just _) -> r
</code>```

In a sense this is dual to the Maybe monad in that a computation stops at the first success instead of at the first failure.

Of course, I can use the function I have written above but I was wondering if there is a better, well-established and idiomatic way of expressing this pattern in Haskell.


答:
The next step beyond 'testing every feature once' is systematic Pairwise Testing. This typically results in a set of a few tens of tests per feature, depending on the features visible complexity. This is obviously a lot more work, although not necessarily tens of times more work, at least if tests are automated. You will almost certainly need a suitable tool.

Alternatively, you could bake in robustness at a lower level, with developer-level unit or integration tests. At that level, instead of writing out tests cases one by one you can use a tool like Quickcheck and/or JUnit theories. Links go to java tools; most languages have something equivalent.

Whether you do either, both or none of those would depend on the nature of the faults you are seeing at UAT, and how much of a priority it really is to reduce or eliminate them.

Title: Testing Scenarios More than Once

Body:
Is there an industry standard in how many times a scenario is tested before it is considered passed?  Is it common to test a given scenario using multiple different records?

Here is the issue:  A development project is now in the SIT phase and the developers' plan is to test each scenario once unless it fails.  There is an opinion that the scenario needs to be tested more than once before considered passed because, in the past, there were defects found during UAT for scenarios that passed in SIT.


问:
When applying the interface segregation, should you separate interfaces for regular setters and mathematical operations?
When applying the interface segregation, should you have separate interfaces for a straightforward setters and interfaces that perform an operation before setting?  For example, say you have a class:

```<code>class FooClass:
     public GettableFoo,
     public SettableFoo
{
    virtual int getRelevantData();
    // member of GettableFoo (which is used by roughly 20 clients)

    virtual void setToOtherFooTemplate(GettableFoo *other);
    // member of SettableFoo (which is used by roughly 20 clients, some of which also need GettableFoo interface)

    void setToSum(GettableFoo *a,GettableFoo *b);
    // requires SettableFoo functions to implement, used by 8 clients, some of which also need SettableFoo interface

    void combineSomeOtherWay(GettableFoo *a,GettableFoo *b);
    // requires SettableFoo functions to implement, used by 4 clients (possibly more in the future), some of which also need SettableFoo interface and/or which require the setToSum function

private:
  // complex data
}
</code>```

The interface segregation principle states that no client should be forced to depend on methods it does not use.  Does that mean that setToSum() and combineSomeOtherWay() should each have their own interfaces?  The answer seems like it should be yes, but I don't think I've ever come across code with interfaces segregated that much.

If the answer to the above is yes, wouldn't that mean if combineSomeOtherWay() were just setToProduct() (multiply) and I used operator overloading for both to implement this in C++, that technically the operator overloading would be breaking the interface segregation principle given the client needs stated above? And if so, wouldn't most instances where operator overloading is used be breaking ISP, and if not, how is it any different from not segregating any of the interfaces in the above class?

答:
I'd suggest you come at the ISP from the perspective of client code.

In how many places is your class being used? Is there any client class that only needs one method but not the other? If all client code needs both, there really doesn't seem to be a case for two interfaces.

If you do have two different places where your class is being used, with each requiring one method but not the other, the Interface Segregation Principle says you should have an interface for each use case. Your class would then explicitly implement two interfaces.

Keep in mind that in the often-cited 'Xerox' story of the invention of the ISP, it was a first step in the decomposition of a God Object. Having two interfaces for your class is fine, but it's worth asking yourself if the class can sensibly be broken in half.  As others have said, there is a close link between the ISP and SRP (Single Responsibility Principle) here.


问:
How can I add properties to subclasses and access them without casting from a superclass?
I'm trying to model a multi-dimensional point class in C#. I have about eight different types of points, and there may be more in the future. Right now, I have a superclass (PointBase) that holds all the common behaviors and data. This data includes only simple properties like doubles, strings, enums, and DateTimes (these are the dimensions). The subclasses (let's say 1Point, 2Point, etc.) all override at least things: the methods that have behavior for calculating two of these dimensions. If this behavior were the only changing thing, I could just use the Strategy + Factory pattern and be done with it (and honestly, I probably will refactor those two simple common behaviors out later).

Unfortunately, I'm stuck because some points add a property or two based on their type, or based on values of other properties in the superclass. For example, for point types 1-7, I don't need an additional Breakeven property, but for type 8, I do (this is problem #1).

In addition (this is problem #2), depending on the Product property (which exists and is set in the superclass, and is an enum), I may need to add a Term enum property that would apply to all subclass points. However, only one of my Product enum values needs a term. The others don't.

This situation is complicated by needing to store lists of these points in a List<PointBase> data structure that hides additional public properties. I'd have to cast each PointBase to a 1Point or 2Point or whatever when I took it out, and this (of course) breaks some design principles (separation, at the very least, I think).

Unfortunately, I'm also trying to display these different points on the same WPF DataGrid (in a scheme where the user can select 1Point or 2Point or whatever, and get the points' public properties displayed in the DataGrid). Although all of this code so far is contained within my model  (in a separate DLL), I'm also unsure of how to represent this polymorphism in my view in a DataGrid. I'm totally fine with allowing the DataGrid to just autogenerate columns based on the points' public properties, but again, passing these points around in a List<PointBase> means that there's no way to get at those additional properties I need to add. I thought of instead adding a virtual Dictionary to the superclass called CustomAttributes to which I would add a string key and string value every time I needed to include some additional properties. But this is very annoying, because flattening a Dictionary for a DataGrid is really hard. I'm worried that this is the only way though...

From what I know (which is limited w.r.t. software engineering), I need something like an abstract factory to capture all this polymorpism. But I'm not exactly sure. To recap, I need:

The ability to add public properties to certain subclasses based on their type. For example, for the 8Point subclass, I need to add a Breakeven property, but this property doesn't make sense for other subclasses.

The ability to add public properties to all subclasses based on values of properties in the superclass. For example, if the Product (set in the superclass) is A, I need an additional property added to all subclasses called Term. This property does not apply or make sense for any other products.

I'm not married to inheritance here (in fact, I'd like to do something more elegant/simpler if possible, such as delegation + interfaces), so I'm open to any solutions. Thank you in advance!

EDIT: To give some more context, here is what my setup looks like right now:

```<code>public abstract class StatisticPointBase
{
    public DateTime EventTime;
    public Product Product; // an enum
    protected double _delta;
    public string Name;
    public double FooSensitivity;
    public double BarSensitivity;
    public double BazSensitivity;
    public double FlopRatio;
    public double FlapCoefficient;
    ...
    public double Value;     // set by overridden CalculateValue
    public double Velocity;  // set by overridden CalculateVelocity

    public PointBase(IDataRepository d, string name, double delta, Product p)
    {
        Name = name;   // just the name, like "Alpha" or "Beta"
        _delta = delta; // follows name, e.g. for Alpha it's always 0.63
        Product = p;
        FooSensitivity = d.GetFooSensitivity(p);
        ... // other setup
    }

    public abstract double CalculateValue();
    public abstract double CalculateVelocity();
}

public class AlphaStatisticPoint
{
    public SimpleStatisticPoint()
    {
        Value = CalculateValue();
        Velocity = CalculateVelocity();
    }

    override double CalculateValue()
    {
        return (fooSensitivity + barSensitivity + bazSensitivity) * Velocity / 2;
    }

    override double CalculateVelocity()
    {
        return FlopRatio * (_delta / FlapCoefficient);
    }
}

public class BetaStatisticPoint
{
    public SimpleStatisticPoint()
    {
        Value = CalculateValue();
        Velocity = CalculateVelocity();
    }

    override double CalculateVelocity()
    {
        return (FlopRatio * 100) * (_delta);
    }

    override double CalculateValue()
    {
        return fooSensitivity * Velocity;
    }
}

// other points...

public class ZetaStatisticPoint
{
    public double Breakeven;

    public SimpleStatisticPoint()
    {
        Value = CalculateValue();
        Velocity = CalculateVelocity();
        Breakeven = CalculateBreakeven();
    }

    override double CalculateVelocity()
    {
        return (FlopRatio * 100) * (_delta);
    }

    override double CalculateValue()
    {
        return fooSensitivity * Velocity;
    }

    override double CalculateBreakeven()
    {
        return 2 * Math.sqrt(fooSensitivity / barSensitivity);
        // This is not defined for other types of statistics, and is only relevant for Zeta-type statistics.
        // For other statistics, we can't even calculate the breakeven; there's no formula for it.
    }
}

public enum Product
{
    Widget,
    Watchet,
    /* Woffet will be added in future, and needs a Term */
}
</code>```

Stuff like Name and Delta should probably be set in the subclasses, since each subclass has one, and each value is unique to each subclass. For example, Alpha's delta value is always 0.63, Zeta's is always 0.21, etc. I'm trying to get away from inheritance though, and the real problem is that Breakeven exists only for Zeta (this is problem #1).

Furthermore (and this is problem #2), I may need to create and set a Term property, but only for Points that have a Product value of Woffet. It doesn't make sense for other products. This property, Term, would be added to all points, so if we're going with inheritance, I'd put it in the superclass. Although I'm starting to think I should just expand Product into a class, and then give it a Term property. But we run into the same problem for the new Product class then: Term only applies to the Woffet product, just like how Breakeven only applies to the Zeta statistic.

I realize that when one comes upon this behavior, it's usually the case the inheritance is not the answer (or so I've gathered?). So, I'm looking for a better way to model this. I was thinking of getting rid of all the subclasses but Zeta, and just giving the superclass a ValueCalculationStrategy and VelocityCalculationStrategy in the constructor (these would calculate Value and Velocity). But in this case, I'm still referring to Zeta as a StatisticPointBase, and the client doesn't know it's a ZetaStatisticPoint. So I'm still stuck. Maybe the problem is that I'm conceptually mixing statistics and points? I could make a separate ZetaStatistic class, and a ZetaBreakeven class, and then use these to compose a ZetaPoint class, but I don't know if this is the right thing to do.

Hopefully I've explained this adequately. If you have any questions, please ask in the comments and I'll do my best to expound on things.

答:
I posted a question here that was brought about by the same problem: trying to both take advantage of the convenience of referring to objects by their base class, while at the same time using additional properties that their subclasses may contain.

The solution that was most useful to me was to use the visitor pattern.  In your Point base class, you define an abstract method void Accept(Visitor).  The Visitor class would define a method for each subclass (so you'd have to keep track of them all, any new subclass would require modifying the visitor class).  For example, the visitor would look like this:

```<code>interface Visitor {

    void on1Point(1Point);

    void on2Point(2Point);

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

Then each BasePoint subclass would implement the accept method to delegate to the correct Visitor method.  So in the 1Point class, accept would be defined as:

```<code>void accept(Visitor visitor) {
    visitor.on1Point(this);
}
</code>```

Now whenever you have a BasePoint and want to do something with it depending on what extra properties it has, make a visitor, figure out what you want it to do in the case of being each possible subclass, and put the logic there.  In the body of the Visitor method, the object you'll be handed will be "cast" to the correct type, so you can access any of its additional properties.  It's similar to just doing a bunch of instanceof checks, but it's much cleaner, more reusable, and more elegant.

Body:
I posted a question here that was brought about by the same problem: trying to both take advantage of the convenience of referring to objects by their base class, while at the same time using additional properties that their subclasses may contain.

The solution that was most useful to me was to use the visitor pattern.  In your Point base class, you define an abstract method void Accept(Visitor).  The Visitor class would define a method for each subclass (so you'd have to keep track of them all, any new subclass would require modifying the visitor class).  For example, the visitor would look like this:

interface Visitor {

    void on1Point(1Point);

    void on2Point(2Point);

    ... etc
}

Then each BasePoint subclass would implement the accept method to delegate to the correct Visitor method.  So in the 1Point class, accept would be defined as:

void accept(Visitor visitor) {
    visitor.on1Point(this);
}

Now whenever you have a BasePoint and want to do something with it depending on what extra properties it has, make a visitor, figure out what you want it to do in the case of being each possible subclass, and put the logic there.  In the body of the Visitor method, the object you'll be handed will be "cast" to the correct type, so you can access any of its additional properties.  It's similar to just doing a bunch of instanceof checks, but it's much cleaner, more reusable, and more elegant.


问:
Behat/Mink: best practice for testing strings in a web application's GUI
I'm writing acceptance tests for a web application using Behat/Mink.

I want to know best practice for testing strings in the GUI. For example: say I want to test that a link exists on the homepage to the login screen, by looking for a link with a text, such as "Log In".

I want to make it robust; at the moment, for example, I am testing for the presence of the link by hard coding the text of the link into the scenario:

```<code>Feature: Website Nagivation
  To use the website
  As a website visitor
  The nagivation needs to work

Scenario: Check that the login link exists on the homepage
  Given I am on "/"
  Then I should see a link labelled "Log In"
</code>```

Obviously this is really fragile. If the link's text is changed to "Sign In" then the test would break. (Among other problems, e.g. if the site is internationalised, the problem would be multiplied).

What strategies can I use for this? For example:

Should I keep the data DRY, so have the strings used to populate the GUI come from the same place as the strings used to test, and refer to the string by some unique identifier?

How could this be made most user-friendly for the writers/readers of the Gherkin/Behat acceptance tests?

答:
Behat is at its best when used a Behaviour Driven Development tool. Try to think of your feature files as requirements, not tests. Change the requirements first, then alter your system to get the tests passing!

To answer specifically your question about languages, if you do have a multi-language site, try putting an extra step like 'Given I'm an Englishman' at the top of your Scenario.

Edit:
Bare in mind that Behat suites can become unwieldy if they're too tightly coupled to the UI all the time though. Consider doing more 'service-level' testing and less 'UI' testing for larger systems. See: http://sam-burns.co.uk/108/testing-pyramid/


答: I'm assuming you're talking about renaming in source code files.  With today's IDEs this should always be done with the IDE's refactoring tools.  If your IDE doesn't have this, consider switching to another IDE.  Most IDE refactoring tools also keep a history of refactoring, giving you the ability to quickly "undo" if you don't like the results of the refactor.  Using search/replace, you may not have the ability to undo the whole set of changes (unless you maybe use your revision control tools and revert to previously committed version).  Also, using refactoring tools you're safer from inadvertently changing something you didn't intend to change.


问:
What would be a reason not to embed JS in C?
I'm working on an opensource application that processes JSON in C, because I would like to make it easier for people to help me in the project and because JSON is so close to JS. I want to embed a JS engine and compile the JS into the software.

The reason I've chosen C for this particular program is because of C's speed. Is there any reason why I shouldn't include JS?
I find it difficult to find any information regarding this particular topic.

答:
No reason why not... people embed Lua in C++ engines all the time, and sometimes JS engines. This enables them to run script-based code (eg for games, levels can be described in script).

However, it does raise a large level of additional complexity that may not be needed if all you want to do is parse JSON. For that get a JSON library for C instead (Spirit or libjson)


问:
Auth options for distributed systems
I am in the process of designing 3 components that will work in symphony with one another:

A RESTful web service which requires BasicAuth over HTTPS on all calls, and which is what actually does all the heavy lifting for my system (does the work)

A web UI that translates end user actions into API calls to the above-mentioned web service; hence the UI is "backed by" the WS

A command-line interface (CLI) tool that developers can install and run locally, that also translates commands into API calls to the WS (hence it too is "backed by" the WS)

One of the first hurdles I'm trying to cross is with respect to authentication and authorization.

Let's pretend that the WS uses a LDAP/directory service (like AD or perhaps Apache DS) as its authentication realm. Meaning, when an API call come in over the wire (say, an HTTPS GET for some resource), the BasicAuth credentials are extracted from the request, and forwarded on to the LDAP service to determine whether this is a valid user or not. If they are authenticated, then let's say that a separate authorization realm, perhaps a database, is used for determining whether or not the identified user can do what they are attempting in the HTTPS request. So far, so good.

In the case of the CLI tool, the user will have to authenticate prior to running any commands, and so this model works just fine, as a single user will only ever be operating the same CLI instance at a given time.

The problem comes when we try integrating the web app (UI) with the WS, because many people could be logged on to the app at the same time, all with different permissions dictating which underlying API calls they're allowed to make.

As far as I see it, it looks like I have but 4 options here:

Cached Credentials: After logging into the app, the credentials are somehow, somewhere cached (such that the app has access to them), and the app doesn't enforce any kind of authorization policy itself. When users attempt to do things that generate API calls under the hood, their credentials are looked up from the cache, and forwarded on with the API calls. If the WS determines they aren't authorized, it sends back an error.

Service-Level Accounts: The app and the WS both use the same authentication/authorization realms, except the web UI now enforces authorization on what users can actually see and do inside the app. If they're allowed to do something that generates an underlying API call, the app sends service account credentials (e.g. myapp-admin-user) with each API call on the user's behalf.

OAuthv2: I have no idea what OAuth is or if its applicable for this scenario, but feel it may be a solution here somehow.

Token Servers: Use a token server such as CAS or maybe Kerberos to vouch for users, in a similar way as the Service-Level Account option behaves. Here, when a user logs into the app successfully, the token server sends the app back a session UUID, and also registers that UUID with the WS. Every time the app generates an API call, it tacks the UUID on to the request, which is then validates on the WS side.

The "Cached Credentials" option just feels like an aberration of everything that is good and wholesome in security-land. It just feels wrong to cache credentials anywhere, ever.

The "Token Server" option seems valid for an SSO type setup, but not in this particular case and feels awkward to me. I also think there's no good way to use the session UUID concept and BasicAuth/HTTPS at the same time.

So this leaves OAuthv2, which I know nothing about, and "Service-Level Account (SLA)*" as the only remaining options. The SLA option seems OK, but has a few following drawbacks:

It requires the service account to basically have "god privileges" over the WS. In other words, once the app deems a user is allowed to click a button or do something in the UI, that translates to an unconditional API call by the service account being used by the UI. This just feels bad, mkay?

It occurs to me that maintaining two sets of permissions (the permission set for each user of the app, and then the permission set for the service account used by the app against the WS) can result with the permissions getting out of synch with each other somehow

So it appears that I don't really have any good options here. Surely I can't be the first dev to run into this, but asking the Google Gods have not helped me much here. Any ideas?

答:
I'm working on a somewhat-similar system right now, actually; I'd be lying if I said that I knew the "right" way to make this work since I'm still experimenting but maybe going over what I've found to work might help. The setup is pretty heavily inspired by OAuth2 despite its drawbacks, some of which I'll discuss.

DISCLAIMER: I'm not a security guy by trade, and what I've built I've built with the help of Google and as many examples as I could find.

When I first started researching how I'd build the web API that would back the client application(s) I decided that I wanted to try and make the API as stateless as possible. Part of me was tempted to reach for HTTP basic auth and make users authenticate on every request, but two issues popped up that made that solution not seem viable:

The lookup to validate the credentials is a non-trivial time expense, as it would involve at least a database call with each request

The system is a multi-tenant system; identifying which of the tenants the user belonged to would require a third parameter and that isn't supported by HTTP basic auth (1)

The complexities involved in authentication made me opt for a token system, where the user would make an authentication request to an endpoint which would issue back an identifying token and then store that somewhere the server could later use it to validate requests and link it up with some necessary user data. It's not perfectly stateless, and I've been looking at JSON web tokens as an alternative approach, but the token lookup can be made very fast. (2)

Clients then hang on to that token until the server no longer accepts the token. The client then attempts to reauthenticate with the server and retrieve a new token to authenticate future requests with. This is what your post references as the cached credentials strategy, and we've opted to use it because it allows us to maintain more control over access to the application. Provided the client can be trusted to hold its own authorization information and is only connecting over a secure connection (we force HTTPS-only access for that reason) that's not necessarily a bad way to handle things, if only from a UX perspective. For the web service we actually hold on to the token in browser local storage; since it's only a temporary identification and not a user's actual username/password combination then we've deemed this "good enough" if not actually good.

The tokens are then sent to the web API as part of an Authorization header, or as a GET parameter for clients where custom HTTP headers are unavailable. This is important because it allows for a greater amount of flexibility in how we access the API from a wide range of potential client applications, a lot like how you need to support a CLI and a web app. Bearer tokens are a fairly common thing but they aren't exactly perfect. Our application's security concerns aren't quite important enough to devote additional time to improving this yet though.

Once the token is validated, authorization comes into play. What that entails can vary widely, but by that point in the application the user's identity is known and so an authorization service of some sort just needs to be given that user's identity and the object/action to check against.

At the very least, if you do want to use this kind of strategy, there's a lot of libraries which are designed to implement OAuth and OAuth2 out there; unless you're like us and have some very fringe requirements, I highly recommend using a trusted third-party security library because you will very likely not get things right the first time you try. I still look around for a third-party alternative to replace our current authentication system because I know it's full of holes and edge cases I can't even begin to imagine.

Footnotes

This wouldn't be necessary if our system was built differently, say by using different points of entry for each client; alternatively I also considered getting clever and prefixing the username with a tenant identifier

I've had some ideas on how to make the token string easy to validate purely computationally instead of having to do an I/O lookup as a long-term target for improvement; at the very least tokens contain a version byte which will allow for upgrades down the line if/when the decoding process for it changes

Title: Auth options for distributed systems


问:
Why create a Logger object instead of using static logging methods across an application?
Taking an example of a simple Ruby on Rails application. It creates a Logger object during application load process:

# in environment.rb
config.logger = Logger.new(<STDOUT | file | whatever>)

# and in our application we use this object
logger.warn "This process is taking too long to process. Optimization needed."
```

My question is, why don't we use class methods (or static methods) for logging? Won't Logger.warn scale than Logger.new.warn? Or atleast Logger.warn seems intuitive than Logger.new.warn.

Even if Logger.new is a singleton object, what advantages does it offer?

答:
Static method invocation should be avoided wherever possible. It's an antiquated alternative to proper Dependency Injection, and not something you'll find helpful in a larger codebase.

Consider testability, for example. Statically invoking logging puts the Subject Under Test in control of which logging class is used - there's no Inversion of Control. There is no possibility to inject a mock object or any kind of fake here.  By injecting the logger into the SUT, you'll find that you have the option to mock the logger and inject it.

The benefits of using DI over the kind of static method invocation under discussion go beyond testability as well, of course. Consider what would happen if you wished to have two different loggers in your system, and the option to change the application behavior through configuration of the object graph alone, without editing existing code.

Overall, I'd suggest you try a DI approach, so you don't find your code untestable and unwieldy later.


答:
There are many reasons not to use basic authentication scheme to protect Web API services.

In order to use the service, the client needs to keep the password somewhere in clear text to send it along with each request.

The verification of a password should be very slow (to counter brute force attacks), which would hamper scalability of your service. On the other hand, security token validation can be quick (digital signature verification).

OAuth2 does offer solutions for each of your use cases. Your web application can use the code grant, which gives it an access token it can use to talk to your API.

Your web application will redirect the user's browser to the authorization server. It will prompt the user for credentials (or smart card, or two-factor auth code) and return a code to the browser, which the client (your web application) can use to get an access token from the authorization server.

Your application will also get back a refresh token with which it can get a new access token if the current token expires.

Your CLI application can use the resource owner credentials grant. You will prompt the user for credentials and submit them to the authorization server to acquire an access and refresh token. Once your CLI application has the token, you can discard the user's password in memory.

Both clients (web app and command-line client) need to be registered up front with the authorization server.

Your authorization server may well talk to a LDAP/directory service (identity provider or IdP) to do the actual authentication.

Your web API service only needs to verify the incoming JWT token and establish what the user is allowed to do (authorization).

If you are the victim of a man-in-the-middle attack and you lose your access token, the attacker only has a limited time (token lifetime) to use it. A password is typically valid for much longer. Refresh tokens can be revoked in case they get lost.

Title: Auth options for distributed systems

Body:
I am in the process of designing 3 components that will work in symphony with one another:

A RESTful web service which requires BasicAuth over HTTPS on all calls, and which is what actually does all the heavy lifting for my system (does the work)

A web UI that translates end user actions into API calls to the above-mentioned web service; hence the UI is "backed by" the WS

A command-line interface (CLI) tool that developers can install and run locally, that also translates commands into API calls to the WS (hence it too is "backed by" the WS)

One of the first hurdles I'm trying to cross is with respect to authentication and authorization.

Let's pretend that the WS uses a LDAP/directory service (like AD or perhaps Apache DS) as its authentication realm. Meaning, when an API call come in over the wire (say, an HTTPS GET for some resource), the BasicAuth credentials are extracted from the request, and forwarded on to the LDAP service to determine whether this is a valid user or not. If they are authenticated, then let's say that a separate authorization realm, perhaps a database, is used for determining whether or not the identified user can do what they are attempting in the HTTPS request. So far, so good.

In the case of the CLI tool, the user will have to authenticate prior to running any commands, and so this model works just fine, as a single user will only ever be operating the same CLI instance at a given time.

The problem comes when we try integrating the web app (UI) with the WS, because many people could be logged on to the app at the same time, all with different permissions dictating which underlying API calls they're allowed to make.

As far as I see it, it looks like I have but 4 options here:

Cached Credentials: After logging into the app, the credentials are somehow, somewhere cached (such that the app has access to them), and the app doesn't enforce any kind of authorization policy itself. When users attempt to do things that generate API calls under the hood, their credentials are looked up from the cache, and forwarded on with the API calls. If the WS determines they aren't authorized, it sends back an error.

Service-Level Accounts: The app and the WS both use the same authentication/authorization realms, except the web UI now enforces authorization on what users can actually see and do inside the app. If they're allowed to do something that generates an underlying API call, the app sends service account credentials (e.g. myapp-admin-user) with each API call on the user's behalf.

OAuthv2: I have no idea what OAuth is or if its applicable for this scenario, but feel it may be a solution here somehow.

Token Servers: Use a token server such as CAS or maybe Kerberos to vouch for users, in a similar way as the Service-Level Account option behaves. Here, when a user logs into the app successfully, the token server sends the app back a session UUID, and also registers that UUID with the WS. Every time the app generates an API call, it tacks the UUID on to the request, which is then validates on the WS side.

The "Cached Credentials" option just feels like an aberration of everything that is good and wholesome in security-land. It just feels wrong to cache credentials anywhere, ever.

The "Token Server" option seems valid for an SSO type setup, but not in this particular case and feels awkward to me. I also think there's no good way to use the session UUID concept and BasicAuth/HTTPS at the same time.

So this leaves OAuthv2, which I know nothing about, and "Service-Level Account (SLA)*" as the only remaining options. The SLA option seems OK, but has a few following drawbacks:

It requires the service account to basically have "god privileges" over the WS. In other words, once the app deems a user is allowed to click a button or do something in the UI, that translates to an unconditional API call by the service account being used by the UI. This just feels bad, mkay?

It occurs to me that maintaining two sets of permissions (the permission set for each user of the app, and then the permission set for the service account used by the app against the WS) can result with the permissions getting out of synch with each other somehow

So it appears that I don't really have any good options here. Surely I can't be the first dev to run into this, but asking the Google Gods have not helped me much here. Any ideas?


问:
How to handle a project in git with the same code but different templates?
I have a project where the only difference are the templates.

The question is how should I manage this with git now?

At the moment I have 3 different git Repos, but it's hard to maintain all 3 of them.

What would be a good solution for this problem?

1 Repo for the Codebase and 3 for the different templates(submodules/subtree)?

Edit:
It's a PHP Project, with templates i mean the gui/frontend(html,css,js...)

```<code>-app
-Resources
    -Template
       -js
       -css
       -html
    -Images
    -Translation
</code>```

答:
A couple of suggestions that might make this easier to handle by changing your project structure a bit.

First, you are right that managing this in three different repos is probably too much work.  Generally I have found that splitting different software components that all seem to make sense to a general project by folder in a repo is a good way to modularize your code and resources.

If you haven't thought about the concepts of Continuous Integration and Continuous Delivery then this is worth looking into.

Continuous Integration

This approach is about mainlining all of your active development threads into a single branch.  Also playing into this is organizing the automation of packaging and versioning your code such that it can be deployed easily.  This can be done through tooling or scripting, I am not sure what tooling is out there for this in PHP, but you should have the ability to package modules of PHP software components (or groups of pages) as well as static resources from a template of your choosing in another folder entirely in your repo.

Continuous Delivery

This discipline and approach is concerning using tooling or scripting to take a packaged build and deploy it one quick to one or many environments for testing or production.

So what does this mean to you, well if you were running on Apache then typically your static resources would be in a separate physical file location that can be served from and this would be mapped to a different context root than typically would be your dynamic PHP page content.  The two could feasibly live in separate file locations so they can probably and should probably be treated like separate independently themed and versioned software components, each with their own packaging behavior and each with their own deployment behavior.

It makes sense to keep your templates in another folder and to be treated like different software modules in your Git repository.

The added benefit of this is with one-click deployments for each type of template build of your choosing, you get 1 step closer to the Joel Test.


问:
Domain driven design with eventual consistency
My domain aggregate is struggling with simple business logic so I feel like I have modeled it incorrectly.

The architecture I have right now uses domain driven design with event sourcing. The domain aggregate produces events which get digested by subscribers. Eventually the event queue will be empty and the view store completely updated.

Where it struggles is with large collections of objects on the aggregate and the need to coordinate between domains.

So one aggregate is a ChatAggregate which allows people to add comments. However a user can only add one comment per hour or one comment for the entire life time. My domain object cannot keep all comments in memory but I still need my ChatAggregate to apply this business logic. Because of the eventually consistent nature of my view store, I cannot let my aggregates query it for business logic. How does DDD handle when an aggregate needs access to a lot of data?

The second issue I have is when a domain command is being processed, I want to query other aggregates before processing the command with the target aggregate. An example is before creating a new ChatCommentAggregate instance, I would like to query the ChatAggregate to see if the chat is still open.

答:
If eventual consistency will not do then you'll need a way to store 100% consistent data on the transactional/write/domain side of things.

That being said, it is sometimes possible to implement a business rule slightly differently but still get the same result.  For instance, you could add a list of ChatAggregateComment value objects to your ChatAggregate that store, say, the UserId, CommentId, and DateCommented.  This list would grow only as big as the number of people involved in the chat.  However, if even that is going to be too large then you could denormalize the data and store this same list as immediately consistent on your write side and then query table through some domain-side query interface.

As far as creating a new ChatCommentAggregate is concerned you could use your ChatAggregate as the factory for a ChatCommentAggregate.  Your rule could be applied within the ChatAggregate.CreateComment method.

OwnerDisplayName: LivingOnACloud


问:
Quicksort and don't bother?
Especially when writing 'standard' (non-HPC) applications, do you consider what sorting algorithm to pick, or just settle with quicksort (which is what most libraries just call sort)? To some extent it may be profitable in specific situations, but on the other hand proper optimization requires some time to analyse the problem and make benchmarks. </p>

答:
At a conference once I heard a nice story about this.

At Microsoft someone was writing a VB app (c. VB 3) and mailed a bunch of people saying that he had a load of values and he wanted them to appear in the combobox in order, how should he go about it.

Everyone dived for their old computer science text books, looking up highly efficient routines and porting them to Visual Basic and mailing them to him.  One guys just mailed back "how many values in the combobox?".

"About 50" came the reply.

"Just set the sorted property to TRUE".

In 99.9999% of instances sorting is best done using a library, control or in the SQL select as the performance difference between the library routine and anything you write will be negligible and the effort and maintenance overhead will massively outweigh the consequences.

ContentLicense: CC BY-SA 2.5

Title: Quicksort and don't bother?