问:
usage of interface.super.print() in java8
In java8, we are using interface.super.

Considering the below points

There are 2 interfaces but none of the interfaces inherit to another.

There is implementation class which is inheriting both of those 2 interfaces.

Each interface has a default method but the name is same for both of those methods.

Now in this scenario, in the implementation class it is forcing me to override the default print() method. And in the body I need to use either

Interface_one.super.print();

or

Interface_two.super.print();

I am new to Java8, I would like to understand the strange behaviours of using the interface.super. Also the implementation of print() method forcing the statements Interface_one.super.print(); or Interface_two.super.print();

 public interface Interface_one {
    public void method1();

    default void print(){
        System.out.println("this is default print in first interface");
    }
}

public interface Interface_two {
public void method2();

    default void print(){
        System.out.println("this is default print in second interface");
    }
}

public class ImplementedClass implements Interface_one, Interface_two{

    @Override
    public void method1() {
        System.out.println("Implemented Method 1");

    }

    @Override
    public void method2() {
        print();
        System.out.println("Implemented Method 2");
    }

    @Override
    public void print() {
        Interface_one.super.print();
    }

    public static void main(String[] args) {
        new ImplementedClass().method2();
    }
}
```

答: One more thing : there is no ambiguity when overriding method as accepted answer is saying, you have to use A.super or B.super only if you want to reuse default implementation , then you tell which print() you want to use as they are two. You can omit calling any of default methods and write completely new implementation or even make that method (and class) abstract.


问:
Is measuring the binary size of a c++ program a good indication of code complexity? Or something else?
In my company we have this obligatory practice before a review to be send the binary size impact of the code change to be measured and provided.

We must use -Os for this metric to avoid unpredictable inlining. There is no customer or product driven arguments for it. It is a big server that is installed as singleton of a dedicated machine, where the executable size is completely ignorable in comparison to all the other resources involved in the system.

The main argument for this practice is that -Os binary size correlates with code complexity.

Is measuring the binary size a reliable metric to use when evaluating code complexity? Or for evaluating anything else?

答:
The size of the binary is pretty much only a good indication of the size of the binary. Code complexity fundamentally stems from "choice" (be that the choice to terminate a loop, a condition in am if statement, a switch or cond block, duck-typing, having multiple classes implementing an interface, ...). For any given binary size, there's a binary of comparable size that is composed entirely of linear, non-branching code.

Change in binary size (which is what you actually seem to be asking about) may or may not correlate to changes in complexity. Is it "more complex" to pull in a well-tested library to do one (or more) things? Probably not in any useful sense, as long as the library interfaces are clean and sufficiently "black box". Would it increase the binary size? Most probably.

ContentLicense: CC BY-SA 3.0


问:
Why do we need a context class in strategy pattern?
For the strategy pattern, why do we need a context class to call the appropriate algorithm? Why can't we just do Strategy s = new OperationAdd()? This way, we still use polymorphism.

答:
Within the Strategy patterns, the Context class is the class that owns the (concrete) Strategy object.

The reason for calling that class Context rather than Client (or something similar) is because the Strategy Pattern is formulated in such a way that this class provides the contextual information that the various Strategy implementations need.

If you have a sorting strategy , then the Strategy Pattern states that the class that holds the actual sorting algorithm to use will also pass the collection that needs to be sorted to the sorting strategy and any comparison object/function that might be needed.


问:
Fixing a bug while working on a different part of the code base
This happened at least once to me. I'm working on some part of the code base and find a small bug in a different part, and the bug stops me from completing what I'm currently trying to do. Fixing the bug could be as simple as changing a single statement.

What do you do in that situation?

Fix the bug and commit it together with your current work

Save your current work elsewhere, fix the bug in a separate commit, then continue your work [1]

Continue what you're supposed to do, commit the code (even if it breaks the build fails some tests), then fix the bug (and the build make tests pass) in a separate commit

[1] In practice, this would mean: clone the original repository elsewhere, fix the bug, commit/push the changes, pull the commit to the repository you're working on, merge the changes, and continue your work.

Edit: I changed number three to reflect what I really meant.

答:
We do #1. #2 sounds good, but i can't say we've had problems with #1 that #2 would fix.

An additional factor in my company is that we build web apps, and our testing is almost entirely through the web interface - roughly, what people call functional testing rather than unit testing. We have all tests pass before checking in. Splitting commits into smaller bits would mean running the tests once for each bit, and that would take up more time. I would love to have a much faster test suite, which would let us do smaller commits, but we just don't have it.

ContentLicense: CC BY-SA 2.5


问:
Passing fields (instance variables) by arguments (parameters) inside an object - does it make sense?
I believe this is language agnostic question - if it's not then please correct me.

Let's say I have a class (code snippet is a kind of 'pseudo code')

```<code>class Car:
  private steering_wheel
  private engine
  public Car(steering_wheel, engine):
    this.steering_wheel = steering_wheel
    this.engine = engine

  public void service():
     clean_steering_wheel()
     repair_engine()

  private void clean_steering_wheel():
    this.steering_wheel.do_stuff()

  private void repair_engine():
    this.engine.do_stuff()
</code>```

which works well! But I could also change private methods a bit and let them use fields (i.e steering_wheel and engine) via arguments, not directly

```<code>   class Car:
  private steering_wheel
  private engine
  public Car(steering_wheel, engine):
    this.steering_wheel = steering_wheel
    this.engine = engine

  public void service():
     clean_steering_wheel(this.steering_wheel)
     repair_engine(this.engine)

  private void clean_steering_wheel(steering_wheel):
    steering_wheel.do_stuff()

  private void repair_engine(engine):
    engine.do_stuff()
</code>```

Let's assume that all parameters(arguments) are passed by reference.

What are the advantages and disadvantages of these solutions? Which is considered as better practice? Which one do you prefer?

答:
Passing the field as an explicit parameter is better
if you're not invoking a method, but a function/static method:
The less data is available in a function,
the more explicit all dependencies are,
the easier it is to reason about that code.
So a function clean_steering_wheel(steering_wheel) will not surprise a user
by actually doing something with the engine.

However, a (private) method will already receive references
to the engine and steering_wheel
via the implicit this parameter.
If you have a this parameter in addition to an explicit steering_wheel parameter,
you are duplicating your data – which can lead to inconsistencies.
In particular, I'd be wondering why you didn't use the steering_wheel from this:
Are you operating on the steering_wheel of a different Car?
On a steering_wheel that does not belong to any Car?

In light of this, it would be less confusing to define clean_steering_wheel as

```<code>private void clean_steering_wheel():
  this.steering_wheel.do_stuff()
</code>```

However, it would be even better to use a free function:

```<code>void function clean_steering_wheel(steering_wheel):
  steering_wheel.do_stuff()

void function repair_engine(engine):
  engine.do_stuff()

class Car:
  ...

  public void service():
    clean_steering_wheel(this.steering_wheel)
    repair_engine(this.engine)
</code>```

, or static method:

```<code>class Car:
  ...

  public void service():
    clean_steering_wheel(this.steering_wheel)
    repair_engine(this.engine)

  private static void clean_steering_wheel(steering_wheel):
    steering_wheel.do_stuff()

  private static void repair_engine(engine):
    engine.do_stuff()
</code>```

Which precise approach to use is quite language-specific, and also has impact on testability.
E.g. in C++, using free functions in an anonymous namespace affords the best encapsulation,
but actively hinders testability.
Private static member functions might be better, since they can be tested by a friend class.
In Java, you can't have free functions but must use “static methods”,
so the discussion is unnecessary.

Body:
Passing the field as an explicit parameter is better
if you're not invoking a method, but a function/static method:
The less data is available in a function,
the more explicit all dependencies are,
the easier it is to reason about that code.
So a function clean_steering_wheel(steering_wheel) will not surprise a user
by actually doing something with the engine.

However, a (private) method will already receive references
to the engine and steering_wheel
via the implicit this parameter.
If you have a this parameter in addition to an explicit steering_wheel parameter,
you are duplicating your data – which can lead to inconsistencies.
In particular, I'd be wondering why you didn't use the steering_wheel from this:
Are you operating on the steering_wheel of a different Car?
On a steering_wheel that does not belong to any Car?

In light of this, it would be less confusing to define clean_steering_wheel as

private void clean_steering_wheel():
  this.steering_wheel.do_stuff()

However, it would be even better to use a free function:

void function clean_steering_wheel(steering_wheel):
  steering_wheel.do_stuff()

void function repair_engine(engine):
  engine.do_stuff()

class Car:
  ...

  public void service():
    clean_steering_wheel(this.steering_wheel)
    repair_engine(this.engine)

, or static method:

class Car:
  ...

  public void service():
    clean_steering_wheel(this.steering_wheel)
    repair_engine(this.engine)

  private static void clean_steering_wheel(steering_wheel):
    steering_wheel.do_stuff()

  private static void repair_engine(engine):
    engine.do_stuff()

Which precise approach to use is quite language-specific, and also has impact on testability.
E.g. in C++, using free functions in an anonymous namespace affords the best encapsulation,
but actively hinders testability.
Private static member functions might be better, since they can be tested by a friend class.
In Java, you can't have free functions but must use “static methods”,
so the discussion is unnecessary.


问:
What alternatives to a singleton are there for a class which only can have one instance?
I need to represent an abstraction over various parts of the hardware for a game. I'm trying to decouple the code that does things like manage the logic of the game from the code that is API/platform specific or any ugly implementation details.

Like this:

```<code>std::unique_ptr<IDevice> device(CreateDevice());

IGraphicsDevice *graphics = device->getGraphicsDevice();
ISoundDevice *sound = device->getSoundDevice();
IWindow *window = device->getWindow();
IJobManager *jobmanager = device->getJobManager();
//etc
</code>```

One solution I've seen was to simply put all of this as globals and initialize them in main, but I'd like to avoid that if I can because I don't really like dealing with globals (and I find them to be "ugly", for the lack of a better word). I also can't allow more than one instance because it requires initialization of libraries which are globally initialized themselves.

What alternatives to the singleton pattern are there for this?

I know that more than one instance would likely lead to errors, is this a bad design decision? Could I do anything different?

答: I would solve this by passing around the IDevice instance to the instances that need it, and only instantiate the class in the main function. This also makes the dependencies more explicit.</p>


答:
This is called the Singleton Pattern and is considered to be an anti-pattern by many people nowadays, since it hides dependencies and makes your code less maintainable.

The necessity for using the singleton pattern may arise from other bad design decisions, but I cannot judge since I know nothing about your architecture and design.

Anyway, let me give you an example how to get rid of this pattern. In a game there will most likely be some kind of main loop which calls everything else. For simplicity let's assume this main loop is contained in an object, but this is not a must. When you create the object that contains the loop, you pass the objects you created in your example code (or rather references to them) to that object. It's possible either to pass them via an appropriate constructor or via setter methods to mention the most common examples. How you do this in you main loop strongly depends on your class design, but you'd be able to perform the rendering something like this

```<code>while(running)
{
    game_state->update();
    renderer->render_state(game_state);
}
</code>```

The adventages of this approach are that you eliminate the need for global objects or singletons and avoid that your objects know how to create your device objects. The only thing your objects have to know is that there are some device abstractions they can use. They do not have to know anything else.

This approach is called Dependency Injection and is considered to be a very important pattern of modern OO-design.

Title: What alternatives to a singleton are there for a class which only can have one instance?

Body:
I need to represent an abstraction over various parts of the hardware for a game. I'm trying to decouple the code that does things like manage the logic of the game from the code that is API/platform specific or any ugly implementation details.

Like this:

```<code>std::unique_ptr<IDevice> device(CreateDevice());

IGraphicsDevice *graphics = device->getGraphicsDevice();
ISoundDevice *sound = device->getSoundDevice();
IWindow *window = device->getWindow();
IJobManager *jobmanager = device->getJobManager();
//etc
</code>```

One solution I've seen was to simply put all of this as globals and initialize them in main, but I'd like to avoid that if I can because I don't really like dealing with globals (and I find them to be "ugly", for the lack of a better word). I also can't allow more than one instance because it requires initialization of libraries which are globally initialized themselves.

What alternatives to the singleton pattern are there for this?

I know that more than one instance would likely lead to errors, is this a bad design decision? Could I do anything different?

Body:
This is called the Singleton Pattern and is considered to be an anti-pattern by many people nowadays, since it hides dependencies and makes your code less maintainable.

The necessity for using the singleton pattern may arise from other bad design decisions, but I cannot judge since I know nothing about your architecture and design.

Anyway, let me give you an example how to get rid of this pattern. In a game there will most likely be some kind of main loop which calls everything else. For simplicity let's assume this main loop is contained in an object, but this is not a must. When you create the object that contains the loop, you pass the objects you created in your example code (or rather references to them) to that object. It's possible either to pass them via an appropriate constructor or via setter methods to mention the most common examples. How you do this in you main loop strongly depends on your class design, but you'd be able to perform the rendering something like this

while(running)
{
    game_state->update();
    renderer->render_state(game_state);
}

The adventages of this approach are that you eliminate the need for global objects or singletons and avoid that your objects know how to create your device objects. The only thing your objects have to know is that there are some device abstractions they can use. They do not have to know anything else.

This approach is called Dependency Injection and is considered to be a very important pattern of modern OO-design.


问:
Streams: what has happened after instantiation but before reading?
I'm trying to grok streams - my world is C# but I suspect the principles are general.

I understand the general principle of reading/writing bytes from/to a store. However, what I don't understand, specifically in a read scenario, is what has happened when you've created an instance of a stream (FileStream, for instance) but have not yet invoked any read methods.

e.g.

```<code>var fileStream = new FileStream( "Test.txt", FileMode.Open )
</code>```

At this point the fileStream.Length property is available to me. This leads me to wonder the following:

Has the FileStream class already read all the bytes in the file
and ascertained the length of the file?

Has the file been able to report its length to the FileStream?

Is the file now already loaded into memory and the filestream is offering that up to me in a chunked fashion?

Am I reading into memory the file's bytes at the time I call the read methods?

答:
A FileStream has its length stored as data about the file. The file is not read yet. Think of a several-GB file - Reading it takes long. But returning the length is quick.

Some other types of Streams do not support seeking and therefore don't return Length. See https://msdn.microsoft.com/en-us/library/system.io.stream.canseek.aspx .

Only when you Read from the file are the bytes actually read from the media into memory. (Sometimes the OS might read ahead data that you did not yet read. But that is an OS implementation.)


答:
The answer to all these questions is: "You don't know!".

Please bear in mind that this is a good thing. The entire point of a stream class is to abstract from the tedious detail of how much to read when, and where to allocate the buffer to store stuff that you've already been given by the controller but not yet delivered to your caller. If you wanted to manage all that yourself, you might as well not use a stream and opt to work directly with open() and read() calls. Usually this is not what you want, so a typical stream class not only manages the details, but in fact hides them completely.

Title: Streams: what has happened after instantiation but before reading?

Body:
I'm trying to grok streams - my world is C# but I suspect the principles are general.

I understand the general principle of reading/writing bytes from/to a store. However, what I don't understand, specifically in a read scenario, is what has happened when you've created an instance of a stream (FileStream, for instance) but have not yet invoked any read methods.

e.g.

```<code>var fileStream = new FileStream( "Test.txt", FileMode.Open )
</code>```

At this point the fileStream.Length property is available to me. This leads me to wonder the following:

Has the FileStream class already read all the bytes in the file
and ascertained the length of the file?

Has the file been able to report its length to the FileStream?

Is the file now already loaded into memory and the filestream is offering that up to me in a chunked fashion?

Am I reading into memory the file's bytes at the time I call the read methods?


问:
the future of commercial products
I'm seeing that the open source solutions are growing rapidly & many companies use them now.  What do you think the future for commercial products or solutions will be?</p>

答:
This debate is so value-loaded that it's become impossible to see the two ideas for what they are: they're just business models.

All software costs someone time and/or money to make and/or use, so any business model is capable of being inappropriate in certain situations.

Different business models exist in every industry and market to (at least temporarily) offset those costs based on the resources available. I don't see why it would be any different for software.

Both business models are capable of hurting people. There are tons of programmers out there that have become incapable of feeding their families because their work had been replaced by open source software that wasn't necessarily better, but happened to cost $0. Meanwhile there are programmers that eat money for breakfast while exploiting their customers.

Either way, both models will continue to exist by necessity if not by ideology.

By the way if you look at rich client software (e.g. online games), it's clear that payment can be enforced for certain kinds of software. Those ones will always be commercial.

Title: the future of commercial products


答:
Has the FileStream class already read all the bytes in the file and ascertained the length of the file?

Has the file been able to report its length to the FileStream?

You can actually look for yourself at the reference source. It looks as if it uses the Win32Native-API. Hence, getting the length of the stream is basically the same as right clicking a file, and viewing the "properties" of it. The size of the file is saved as meta-data. So in short; no, it does not read the entire file. From top to end, most implementations of Stream does not, this would defeat the purpose of streaming.

Is the file now already loaded into memory and the filestream is that up to me in a chunked fashion?

No, a FileStream is what it says on the tin, a file stream, it "streams" data from the file. If you copy the FileStream to a MemoryStream, then it's an in-memory stream.

Am I reading into memory the file's bytes at the time I call the read methods?

Yes.

To clarify, when you call ReadByte() you are reading one byte into memory, from the streams Position. When you call Read() you are reading the specified amount of bytes into memory (your buffer).

One of the main points of having a stream, is not to have to store something in memory. A byte-array does this, MemoryStream is in fact basically a wrapper for a byte array/buffer.


问:
Is client-side validation really all that important, always?
Through the years I've worked in web development it's been ingrained in me that client-side validation is absolutely and completely necessary in all web applications. Seems to me like all the people in the profession are very adamant on using it every single time. The most commonly mentioned benefits are:

Instantaneous showing of form errors

Less unnecessary requests to the server

But as we're moving towards the modern web, more and more applications are AJAX based. The simple task of submitting forms takes a lot less time now than it did before and validating on the server and returning errors barely impacts the user experience.

Could it be justifiable to completely avoid client-side validation (for example) on an application that only contains small and simple forms?

EDIT: I would argue that the linked duplicate question doesn't really capture the same example I'm giving here. A lot has changed since 2011. All of the answers on the related question are arguing for user experience whereas in my question I'm describing a scenario where the user experience would be unaffected.

When client-side validation no longer improves the user experience does it continue to rank in the same level of importance as before?

答:
While I agree with JacquesB, if you can provide the same level of interaction server side, then client side validation isn't always needed - however some other points to consider.

Point A (Speed): Client side validation is intended to be instant, as in 100% instant. While network speeds are improving, you're unlikely to be able to guarantee that this speed will be constant, and for everybody. Client side validation will generally always outperform the latency of a network request.

Point B (Performance): Server side validation, by definition is performed on the server. If you're working on a high traffic application on a budget server then saving additional requests no matter how small can make an impact in overall performance. Especially if we consider Point A where the latency can lead to multiple submission from the user, awaiting feedback.

Point C (Flexibility): Some validation isn't necessarily based on the value of a field, but can be based on the order or mechanism or populating a field. For example if a user copies and paste's into a password or email field, commonly this is nullified by javascript. This level of validation (which I believe this functionality still falls under) couldn't be achieved server side.

When client-side validation no longer improves the user experience does it continue to rank in the same level of importance as before?

While this is a valid question - it's alittle too abstract to answer yet. It's hard to imagine in the next year or so that this will ever become true, and as Point C covers, client side validation is often used to validate the users behaviour, not just values, which again is hard to imagine being managed server side.

Finally, as everybody already knows. Client side validation isn't robust enough to use solely on it's own. So just to reinforce the point, don't rely on client side validation without also checking server side. This includes javascript validation and validation included in the HTML5 spec built into certain input types.


问:
How are head first books?
I have never read any of them but I find their style interesting and unique.  I am not sure if they are worth giving money/time?</p>

答:
I don't know about the other Head First books so I'm going to state my opinion about the book that I'm reading right now, Head First Servlets and JSP.

The first half of the book is definitely great, hands down. They explained the concepts in a straight-forward fashion through pictures and stories. As a developer who built a J2EE web app in the wrong way as a way of diving in, I found the book really helpful in patching up some of the holes in my knowledge of J2EE. Most of the questions I find myself asking when I was still starting out was answered by the first half of the book.

However, I find the remaining half of the book to be written as if it was intended for advanced developers already. The book makes you dive into several advanced topics and concepts without really explaining how everything happened in words that beginners can understand. The book tosses you several topics at once, so it's giving me a hard time to understand everything. I even find the diagrams, and pictures to be confusing as well.

I'm still on the process of reading the book right now, but I'm now under the impression that the book was rushed, because the book failed to explain the topics clearly that I can't piece everything in my head together now. This dilemma led me to ask this question.

I don't know if other Head First books are the same way since I haven't read anything other than Servlets and JSP.

Title: How are head first books?


问:
How do you follow the evolution of requirements?
What are the ways of managing the evolving requirements without turning them into a mess?

We do not have a dedicated analyst in our team so this role is shared by all the members.

Our reoccurring workflow is the following:

Users send us the initial version of requirements for new
functionality which is then followed by a discussion with many
questions and clarifications.

After functionality is implemented and new version of application is
deployed users can play with it, and decide what they like, and what
they don't. Very likely they ask for some changes or additions. And
the cycle repeats.

Nobody summarizes the requirements in a document approved by the
users. We just store msg files in the archive.

After N iterations it's quite painful to restore the whole discussion
and understand why system behaves now as it does and what its
evolution was. Especially it is difficult to explicitly emphasize
client's decisions.

Ideally I'd prefer to have some system which allows to store and compare versions of documents, and attach discussions both to the whole document and the particular change. Yet, I am unaware of such a software.

Could you provide some advice or methodology for managing requirements?

答:
If your team is small or you can't dramatically change your process.....

Could you provide some advice or methodology for managing requirements?

Some sort of document management system. Preferably with version history and dates.

As horrible as SharePoint is for many things, it is a good tool for this. Depending on your implementation you can also add signoffs/approvals.

With something like this, you can just look through the revision history.

Or use SVN. It has a good office functionality too to compare different office versions.

Nobody summarizes the requirements in a document approved by the users. We just store msg files in the archive.

Have a main requirements document. Setup a process to add/remove to this. Perhaps have it associated with user testing.

Worst case is you save new copies of UserRequirements.docx as 2015_11_18_UserRequirements.docx and have an archive of them. Or something equally as bad.

But regardless you need a way to have a "master" user requirements process with history. You will need to setup a process with your business team, so they understand they must update this document (not send you an email) if they want formal changes.

OwnerDisplayName: voroninp

OwnerDisplayName: enderland


问:
Should we test all our methods?
So today I had a talk with my teammate about unit testing. The whole thing started when he asked me "hey, where are the tests for that class, I see only one?". The whole class was a manager (or a service if you prefer to call it like that) and almost all the methods were simply delegating stuff to a DAO so it was similar to:

```<code>SomeClass getSomething(parameters) {
    return myDao.findSomethingBySomething(parameters);
}
</code>```

A kind of boilerplate with no logic (or at least I do not consider such simple delegation as logic) but a useful boilerplate in most cases (layer separation etc.). And we had a rather lengthy discussion whether or not I should unit test it (I think that it is worth mentioning that I did fully unit test the DAO). His main arguments being that it was not TDD (obviously) and that someone might want to see the test to check what this method does (I do not know how it could be more obvious) or that in the future someone might want to change the implementation and add new (or more like "any") logic to it (in which case I guess someone should simply test that logic).

This made me think, though. Should we strive for the highest test coverage %? Or is it simply an art for art's sake then? I simply do not see any reason behind testing things like:

getters and setters (unless they actually have some logic in them)

"boilerplate" code

Obviously a test for such a method (with mocks) would take me less than a minute but I guess that is still time wasted and a millisecond longer for every CI.

Are there any rational/not "flammable" reasons to why one should test every single (or as many as he can) line of code?

答:
A resounding YES with TDD (and with a few exceptions)

Controversial alright, but I'd argue that anyone who answers 'no' to this question is missing a fundamental concept of TDD.

For me, the answer is a resounding yes if you follow TDD. If you aren't then no is a plausible answer.

The DDD in TDD

TDD is often quoted as having thee main benefits.

Defence

Ensuring the code may change but not its behaviour.

This allows the ever so important practice of refactoring.

You gain this TDD or not.

Design

You specify what something should do, how it should behaves before implementing it.

This often means more informed implementation decisions.

Documentation

The test suite should serve as the specification (requirements) documentation.

Using tests for such purpose mean that the documentation and implementation are always in consistent state - a change to one means a change to other. Compare with keeping requirements and design on separate word document.

Separate responsibility from implementation

As programmers, it is terribly tempting to think of attributes as something of significance and getters and setter as some sort of overhead.

But attributes are an implementation detail, while setters and getters are the contractual interface that actually make programs work.

It is far more important to spell that an object should:

Allow its clients to change its state

and

Allow its clients to query its state

then how this state is actually stored (for which an attribute is the most common, but not the only way).

A test such as

```<code>(The Painter class) should store the provided colour
</code>```

is important for the documentation part of TDD.

The fact that the eventual implementation is trivial (attribute) and carries no defence benefit should be unknown to you when you write the test.

The lack of round-trip engineering...

One of the key problems in the system development world is the lack of  round-trip engineering1 - the development process of a system is fragmented into disjointed sub-processes the artifacts of which (documentation, code) are often inconsistent.

1Brodie, Michael L. "John Mylopoulos: sewing seeds of conceptual modelling." Conceptual Modeling: Foundations and Applications. Springer Berlin Heidelberg, 2009. 1-9.

...and how TDD solves it

It is the documentation part of TDD that ensures that the specifications of the system and its code are always consistent.

Design first, implement later

Within TDD we write failing acceptance test first, only then write the code that let them pass.

Within the higher-level BDD, we write scenarios first, then make them pass.

Why should you exclude setters and getter?

In theory, it is perfectly possible within TDD for one person to write the test, and another one to implement the code that makes it pass.

So ask yourself:

Should the person writing the tests for a class mention getters and setter.

Since getters and setters are a public interface to a class, the answer is obviously yes, or there will be no way to set or query the state of an object.

Obviously, if you write the code first, the answer may not be so clearcut.

Exceptions

There are some obvious exceptions to this rule - functions that are clearcut implementation detail and clearly not part of the design of the system.

For instance, a the local method 'B()':

```<code>function A() {

    // B() will be called here

    function B() {
        ...
    }
}
</code>```

Or the private function square() here:

```<code>class Something {
private:
    square() {...}
public:
    addAndSquare() {...}
    substractAndSquare() {...}
}
</code>```

Or any other function that is not part of a public interface that needs spelling in the design of the system component.

Title: Should we test all our methods?

Body:
A resounding YES with TDD (and with a few exceptions)

Controversial alright, but I'd argue that anyone who answers 'no' to this question is missing a fundamental concept of TDD.

For me, the answer is a resounding yes if you follow TDD. If you aren't then no is a plausible answer.

The DDD in TDD

TDD is often quoted as having thee main benefits.

Defence

Ensuring the code may change but not its behaviour.

This allows the ever so important practice of refactoring.

You gain this TDD or not.

Design

You specify what something should do, how it should behaves before implementing it.

This often means more informed implementation decisions.

Documentation

The test suite should serve as the specification (requirements) documentation.

Using tests for such purpose mean that the documentation and implementation are always in consistent state - a change to one means a change to other. Compare with keeping requirements and design on separate word document.

Separate responsibility from implementation

As programmers, it is terribly tempting to think of attributes as something of significance and getters and setter as some sort of overhead.

But attributes are an implementation detail, while setters and getters are the contractual interface that actually make programs work.

It is far more important to spell that an object should:

Allow its clients to change its state

and

Allow its clients to query its state

then how this state is actually stored (for which an attribute is the most common, but not the only way).

A test such as

(The Painter class) should store the provided colour

is important for the documentation part of TDD.

The fact that the eventual implementation is trivial (attribute) and carries no defence benefit should be unknown to you when you write the test.

The lack of round-trip engineering...

One of the key problems in the system development world is the lack of  round-trip engineering1 - the development process of a system is fragmented into disjointed sub-processes the artifacts of which (documentation, code) are often inconsistent.

1Brodie, Michael L. "John Mylopoulos: sewing seeds of conceptual modelling." Conceptual Modeling: Foundations and Applications. Springer Berlin Heidelberg, 2009. 1-9.

...and how TDD solves it

It is the documentation part of TDD that ensures that the specifications of the system and its code are always consistent.

Design first, implement later

Within TDD we write failing acceptance test first, only then write the code that let them pass.

Within the higher-level BDD, we write scenarios first, then make them pass.

Why should you exclude setters and getter?

In theory, it is perfectly possible within TDD for one person to write the test, and another one to implement the code that makes it pass.

So ask yourself:

Should the person writing the tests for a class mention getters and setter.

Since getters and setters are a public interface to a class, the answer is obviously yes, or there will be no way to set or query the state of an object.

Obviously, if you write the code first, the answer may not be so clearcut.

Exceptions

There are some obvious exceptions to this rule - functions that are clearcut implementation detail and clearly not part of the design of the system.

For instance, a the local method 'B()':

function A() {

    // B() will be called here

    function B() {
        ...
    }
}

Or the private function square() here:

class Something {
private:
    square() {...}
public:
    addAndSquare() {...}
    substractAndSquare() {...}
}

Or any other function that is not part of a public interface that needs spelling in the design of the system component.


答:
The first thing that you are going to want to do is to define a requirements management process. You're going to want to consider multiple facets: receiving customer/user requirements at the start of a project, elicitation from all stakeholders (including business and regulatory requirements), deriving requirements, capturing requirements, validating requirements, tracing requirements to their point of origin and to artifacts (design, code, tests) as appropriate, and managing incoming change requests (including source and rationale).

The next thing to do is to appoint a person to be the requirements manager. I'm not sure how your organization and projects are structured, but I prefer a product-centric approach where that's possible, where every product is managed as an item. Therefore, every product would have a primary (and hopefully a backup) person to manage the requirements for that product.

Once you have a process and a person (or people) to lead the execution of that process, you're going to want to look at the tools you need to support that process. There are tools designed to support requirements engineering - I'm familiar with IBM Rational DOORS, but there are lots of tools, and I'm sure that there are some that are even free and open source. There are also application lifecycle management (ALM) tools that include requirements management, but go beyond to other facets of software development.

Your approach of using documents is, in my experience, going to lead to problems in the long term, especially if you maintain multiple products or a software product line. You're going to want to maintain your requirements in a tool that supports requirements engineering best practices, and then be able to export to spreadsheets and documents when necessary.

Title: How do you follow the evolution of requirements?

Body:
What are the ways of managing the evolving requirements without turning them into a mess?

We do not have a dedicated analyst in our team so this role is shared by all the members.

Our reoccurring workflow is the following:

Users send us the initial version of requirements for new
functionality which is then followed by a discussion with many
questions and clarifications.

After functionality is implemented and new version of application is
deployed users can play with it, and decide what they like, and what
they don't. Very likely they ask for some changes or additions. And
the cycle repeats.

Nobody summarizes the requirements in a document approved by the
users. We just store msg files in the archive.

After N iterations it's quite painful to restore the whole discussion
and understand why system behaves now as it does and what its
evolution was. Especially it is difficult to explicitly emphasize
client's decisions.

Ideally I'd prefer to have some system which allows to store and compare versions of documents, and attach discussions both to the whole document and the particular change. Yet, I am unaware of such a software.

Could you provide some advice or methodology for managing requirements?


问:
Testing a function that only calls one or two other functions

The short version

The code

As part of TDD, we often end up with functions that follow this pattern:

```<code>function onSendRequestForSelected() {
    this.deselectStepsWithRequest();
    this.sendRequestForSelected();
}
</code>```

Each of the internally called functions has their own unit tests.

The tests

Our unit tests for this function end up pretty much ensuring the function body calls were made:

```<code>expect( iStep.deselectStepsWithRequest ).toHaveBeenCalled();
expect( iStep.sendRequestForSelected ).toHaveBeenCalled();
</code>```

The problem

The problem is:

Our tests end up testing function calls rather than behaviour.

We're unsure what is exactly the purpose of these tests - they protect from nothing other than any future changes.

Nor do they serve as a design documentation.

They clearly test the how rather than what.

The long version

Starting point

We start with the test:

```<code>it( 'should send a request for each of the selected steps', ... )
</code>```

And then implement:

```<code>function onSendRequestForSelected() { ... }
</code>```

So far so good.

New requirement, refactoring

Then we realise we need to deselect steps that already have a request.

So we refactor:

```<code>it( 'should send a request for each of the selected steps', ... )
</code>```

becomes the test for

```<code>function sendRequestForSelected() { ... }
</code>```

and create

```<code>it( 'should deselect steps that already has a request', ... )
</code>```

implemented by

```<code>function deselectStepsWithRequest() { ... }
</code>```

The rubbish test

and then introduce:

```<code>function onSendRequestForSelected() {
    this.deselectStepsWithRequest();
    this.sendRequestForSelected();
}
</code>```

but no idea how to test it.

```<code>it( 'should send a request for each of the selected steps', ... )
</code>```

makes little sense as the test itself only ensure a function is called.

```<code>expect( iStep.deselectStepsWithRequest ).toHaveBeenCalled();
expect( iStep.sendRequestForSelected ).toHaveBeenCalled();
</code>```0

seems like a rubbish test.

The question

So it seems you end up with two options, neither is ideal. Which one is better?

Given TDD we start with:

```<code>expect( iStep.deselectStepsWithRequest ).toHaveBeenCalled();
expect( iStep.sendRequestForSelected ).toHaveBeenCalled();
</code>```1

Option 1

```<code>expect( iStep.deselectStepsWithRequest ).toHaveBeenCalled();
expect( iStep.sendRequestForSelected ).toHaveBeenCalled();
</code>```2

Problems:

The actual sub-functions are not tests (if they would they would be redundant). Dangerous if they will be reused (consider them being needed by other functions).

Option 2

```<code>// No test

function onSendRequestForSelected() {
    // Test for each of the following
    this.deselectStepsWithRequest();
    this.sendRequestForSelected();
}
</code>```

Problems:

This is not really TDD; this is not how we started.

No test to serve as a design documentation. We do not define the behaviour.

In graphical form

Where do you drop the tests?

Testing F1 and F2 only will yield redundant tests for S2.

Testing for S1, S2, and S3 will not test for the behaviour of F1 and F2.

答:
This is obviously a controversial topic.

Having consulted a multitude of opinions, the conclusion is that this is correct:

Given the method

```<code>function onSendRequestForSelected();
</code>```

and its pre-implementation tests:

```<code>it( 'should deselect steps that already has a request', ... )
it( 'should send a request for each of the selected steps', ... )
</code>```

the eventual implementation shall be:

```<code>function onSendRequestForSelected() {
    this.deselectStepsWithRequest();
    this.sendRequestForSelected();
}
</code>```

and the eventual tests shall be:

```<code>it( 'should deselect steps that already has a request', function(){
    expect( iStep.deselectStepsWithRequest ).toHaveBeenCalled();
});

it( 'should send a request for each of the selected steps', function(){
    expect( iStep.sendRequestForSelected ).toHaveBeenCalled();
});
</code>```

Reasoning

Much of the reasoning behind this is based on my argument why you should write a test for every method (well nearly), including setters and getters.

In short:

TDD is not only about defence, but also design and documentation.

For design and documentation purposes, tests shall be written before implementation.

This is a fundamental principle of TDD so it may sound elementary.

But the question needed to be asked is: "Can someone implement this part of the system based on the provided tests?".

So if there is no test, there will be no implementation.

Test are subject to refactoring and extractions much as implementation code is.

Test extraction

So basically, the expect line here:

```<code>it( 'should deselect steps that already has a request', function(){
    expect( iStep.deselectStepsWithRequest ).toHaveBeenCalled();
});
</code>```

is a way of saying:

The test condition, instead of being satisfied here will be satisfied by calling deselectStepsWithRequest()

(for which there is a separate test).

Is like code extraction

much in a way this.deselectStepsWithRequest() in here:

```<code>function onSendRequestForSelected() {
    this.deselectStepsWithRequest();
}
</code>```

is a way of saying

Instead the execution code being here, it is in deselectStepsWithRequest().

Body:
This is obviously a controversial topic.

Having consulted a multitude of opinions, the conclusion is that this is correct:

Given the method

function onSendRequestForSelected();

and its pre-implementation tests:

it( 'should deselect steps that already has a request', ... )
it( 'should send a request for each of the selected steps', ... )

the eventual implementation shall be:

function onSendRequestForSelected() {
    this.deselectStepsWithRequest();
    this.sendRequestForSelected();
}

and the eventual tests shall be:

it( 'should deselect steps that already has a request', function(){
    expect( iStep.deselectStepsWithRequest ).toHaveBeenCalled();
});

it( 'should send a request for each of the selected steps', function(){
    expect( iStep.sendRequestForSelected ).toHaveBeenCalled();
});

Reasoning

Much of the reasoning behind this is based on my argument why you should write a test for every method (well nearly), including setters and getters.

In short:

TDD is not only about defence, but also design and documentation.

For design and documentation purposes, tests shall be written before implementation.

This is a fundamental principle of TDD so it may sound elementary.

But the question needed to be asked is: "Can someone implement this part of the system based on the provided tests?".

So if there is no test, there will be no implementation.

Test are subject to refactoring and extractions much as implementation code is.

Test extraction

So basically, the expect line here:

it( 'should deselect steps that already has a request', function(){
    expect( iStep.deselectStepsWithRequest ).toHaveBeenCalled();
});

is a way of saying:

The test condition, instead of being satisfied here will be satisfied by calling deselectStepsWithRequest()

(for which there is a separate test).

Is like code extraction

much in a way this.deselectStepsWithRequest() in here:

function onSendRequestForSelected() {
    this.deselectStepsWithRequest();
}

is a way of saying

Instead the execution code being here, it is in deselectStepsWithRequest().


问:
Resistance to abstraction
I am on an ASP.NET MVC project where we use Razor to define pages. One thing I like to do is to use Razor's @helper to DRY up pretty much any duplication in HTML (i.e. formalize even small UI patterns). To give an example. At the top of the page there are 3 "quick links" buttons at the top of the page, titled A, B and C. That take user to pages A, B and C respectively. I could type out three times:

A

but I do:

@Link("A", "a")

Please note, my question is not weather this approach is right or wrong. The question is not about benefits of abstractions for maintenance. I have a very specific question here.

What I am often faced with is this desire (not an argument) to "see raw HTML". I want to understand where does this desire to see "raw HTML" comes from. People often say "maybe it is the anguish back from the days of WebForms where all that abstraction was painful".

Why do people yearn to grind through noise to get to the relevant data?

答:
Because they are intelligent, experienced and professional software developers.

Separating abstraction layers is an absolutely crucial part of isolating any problem. One of the very first steps in producing a testcase to reproduce a bug (be it physically, or virtually in your head) is in taking your multi-layered application and examining its layers one at a time.

So, for example:

does the information on the screen look correct?

does the HTML that your browser uses to render it look correct?

do the Razor directives look correct?

does the data in the database look correct?

This is why questions on Stack Overflow that are about all of MySQL, PHP and HTML at the same time really grind my gears. The OP should be narrowing down the problem to one technological layer before posting: that may very well involve finding out what the "raw HTML" is that's sent to the browser for rendering.

I cannot fathom what pain you must endure trying to understand, maintain and debug an application without performing this basic step. Divide and conquer!

Title: Resistance to abstraction


问:
Which pattern can I use for doing computations involving similar yet different object subtypes?
How do I design code that has two qualities:

uses similar but different subtypes of an object

uses similar but different types of computation on the above objects

Example

I am refactoring this from a legacy code that had if/then/else statements for different object types in one file, and if/then/else statements for doing various computing tasks with the objects in another file.

Using OOP I can rewrite it somewhat like this:

```<code>class Pricing {
    public $base;
}

class PumpPricing extends Pricing {
    public $pumpCost;
    public $pumpOption1;
};
class MotorPricing extends Pricing {
    public $motorCost;
    public $motorOption1;
};
class PartPricing extends Pricing {
    public $partCost;
};
</code>```

Later . . .

```<code>//I can put proper object creation into Factory:
$pricing = (new PriceFactory())->getPriceObject("motor");

//but how do I compartmentalize computations?
//i.e. this:

if  (get_class($pricing) == "PumpPricing") {
    $json = array( //future json
        'total' => $pricing->pumpCost + $pricing->base + $pricing->pumpOption1,
        'pump_option_1' => $pricing->pumpOption1
    );
}
else if (get_class($pricing) == "MotorPricing") {
    $json = array(
        'total' => $pricing->motorCost + $pricing->base + $pricing->motorOption1,
        'motor_option_1' => $pricing->motorOption1
    );
}
</code>```

Question

Considering my goal to get rid of if/then/else statements in the mainstream code and to encapsulate the computations, where and how do I do that?

For one, I can group the above formulas into a single computational getter, and put it into the Pricing object.  i.e. to mimic line from above:

```<code>'total' => $pricing->getTotal(),
'motor_option_1' => $pricing->getOption1()
</code>```

But, I am still dealing with different options that I want to group into an array, i.e. names and quantity of the options are different.

答:
You have two problems here:

You need to serialize an object model with differences in the names of the keys, but containing the same basic data (a price and an option)

You need to perform some specific calculations in a generic manner

This requires two solutions.

First, let's tackle performing calculations, because this solution will set us up to solve our data serialization issue. What you really want is the Strategy Pattern:

In computer programming, the strategy pattern (also known as the policy pattern) is a software design pattern that enables an algorithm's behavior to be selected at runtime. The strategy pattern

defines a family of algorithms,

encapsulates each algorithm, and

makes the algorithms interchangeable within that family.

This is precisely what you are trying to do. First, you want to define a public interface for your strategy objects that:

Calculates the price

Returns some sort of "name" for the strategy (useful for building the JSON array)

Returns the "option" price (again, useful for building the JSON array)

interface PricingStrategy
{
    public function calculatePrice();
    public function getName();
    public function getOption();
}
```

<p>Since the algorithm for the pricing strategy is the same in your code example, and only a few values change, we can implement an abstract base class, and then extend it to provide specific values:</p>

```abstract class ProductPricingStrategy implements PricingStrategy
{
    private $name;
    private $basePrice;
    private $cost;
    private $option;

    protected function __construct($name, $basePrice, $cost, $option) {
        $this->name = $name;
        $this->basePrice = $basePrice;
        $this->cost = $cost;
        $this->option = $option;
    }

    protected function getBasePrice() {
        return $this->basePrice;
    }

    protected function getCost() {
        return $this->cost;
    }

    public function getOption() {
        return $this->option;
    }

    public function calculatePrice() {
        return $this->basePrice + $this->cost + $this->option;
    }

    public function getName() {
        return $this->name;
    }
}
```

<p>This gives you the basic framework for easily creating specific pricing strategies:</p>

```class PumpPricingStrategy extends ProductPricingStrategy
{
    public function __construct() {
        parent::__construct('pump', 1000, 250, 49.99);
    }
}

class MotorPricingStrategy extends ProductPricingStrategy
{
    public function __construct() {
        parent::__construct('motor', 5000, 1500, 350);
    }
}

class PartPricingStrategy extends ProductPricingStrategy
{
    public function __construct() {
        parent::__construct('part', 50, 20, 4.99);
    }
}
```

<p>Each concrete class calls the <code>protected</code> parent constructor, and provides all the values necessary for the strategy. Now, we just need a "factory" object to provide easy, parameterized access to these strategies:</p>

```class PricingStrategyFactory
{
    private $strategies;

    public function __construct() {
        $this->strategies = array(
            new PumpPricingStrategy(),
            new MotorPricingStrategy(),
            new PartPricingStrategy()
        );
    }

    public function find($name) {
        foreach ($this->strategies as $strategy) {
            if ($strategy->getName() == $name) {
                return $strategy;
            }
        }

        throw new Exception("Pricing Strategy '$name' not found");
    }
}
```

<p>Lastly, we can refactor the code in question and reduce it to just 6 lines of code that don't require any <code>if</code>s, <code>switch</code>s, <code>and</code>s (or buts):</p>

```$factory = new PricingStrategyFactory();
$pricing = $factory->find('motor');
$json = array(
    'total' => $pricing->calculatePrice(),
    "{$pricing->getName()}_option_1" => $pricing->getOption()
);
```

<p>The <code>getName</code> method is used to generate the unique JSON array key that your response is expecting. The <code>calculatePrice</code> method becomes a black box that encapsulates the algorithm, so the rest of your code base doesn't need to know it.</p>

<p>You'll also notice that the <code>PricingStrategy</code> interface isn't referenced any place else but the definition of the interface, and the <code>ProductPricingStrategy</code> class. In the short code example above you won't see the benefit of the interface. When you need to pass this pricing strategy object around, you'll see the benefit.</p>

<p>First, let's pretend we have a fictional MVC framework, and we've created a "controller" class called "ProductPricesController". The MVC framework routes GET requests for <code>/product_prices/calculate?type=ABC</code> to the <code>ProductPricesController#calculate</code> method:</p>

```class ProductPricesController extends Controller
{
    // GET: /product_prices/calculate?type=motor

    public function calculate() {
        $type = $_GET['type'];
        $factory = new PricingStrategyFactory();
        $pricing = $factory->find($type);
        $json = $this->getPriceJson($pricing);

        echo json_encode($json);
    }

    private function getPriceJson(PricingStrategy $pricing) {
        return array(
            'total' => $pricing->calculatePrice(),
            "{$pricing->getName()}_option_1" => $pricing->getOption()
        );
    }
}
```

The getPriceJson method has a PHP Type Hint: PricingStrategy, which is the name of our interface. This helps the developer because it gives them information about what this method expects, and it helps the application because the interface becomes a "contract" between the controller and the pricing strategy so the two can interact in a predictable and modular manner.

Body:
You have two problems here:

You need to serialize an object model with differences in the names of the keys, but containing the same basic data (a price and an option)

You need to perform some specific calculations in a generic manner

This requires two solutions.

First, let's tackle performing calculations, because this solution will set us up to solve our data serialization issue. What you really want is the Strategy Pattern:

In computer programming, the strategy pattern (also known as the policy pattern) is a software design pattern that enables an algorithm's behavior to be selected at runtime. The strategy pattern

defines a family of algorithms,

encapsulates each algorithm, and

makes the algorithms interchangeable within that family.

This is precisely what you are trying to do. First, you want to define a public interface for your strategy objects that:

Calculates the price

Returns some sort of "name" for the strategy (useful for building the JSON array)

Returns the "option" price (again, useful for building the JSON array)

interface PricingStrategy
{
    public function calculatePrice();
    public function getName();
    public function getOption();
}

Since the algorithm for the pricing strategy is the same in your code example, and only a few values change, we can implement an abstract base class, and then extend it to provide specific values:

abstract class ProductPricingStrategy implements PricingStrategy
{
    private $name;
    private $basePrice;
    private $cost;
    private $option;

    protected function __construct($name, $basePrice, $cost, $option) {
        $this->name = $name;
        $this->basePrice = $basePrice;
        $this->cost = $cost;
        $this->option = $option;
    }

    protected function getBasePrice() {
        return $this->basePrice;
    }

    protected function getCost() {
        return $this->cost;
    }

    public function getOption() {
        return $this->option;
    }

    public function calculatePrice() {
        return $this->basePrice + $this->cost + $this->option;
    }

    public function getName() {
        return $this->name;
    }
}

This gives you the basic framework for easily creating specific pricing strategies:

class PumpPricingStrategy extends ProductPricingStrategy
{
    public function __construct() {
        parent::__construct('pump', 1000, 250, 49.99);
    }
}

class MotorPricingStrategy extends ProductPricingStrategy
{
    public function __construct() {
        parent::__construct('motor', 5000, 1500, 350);
    }
}

class PartPricingStrategy extends ProductPricingStrategy
{
    public function __construct() {
        parent::__construct('part', 50, 20, 4.99);
    }
}

Each concrete class calls the protected parent constructor, and provides all the values necessary for the strategy. Now, we just need a "factory" object to provide easy, parameterized access to these strategies:

class PricingStrategyFactory
{
    private $strategies;

    public function __construct() {
        $this->strategies = array(
            new PumpPricingStrategy(),
            new MotorPricingStrategy(),
            new PartPricingStrategy()
        );
    }

    public function find($name) {
        foreach ($this->strategies as $strategy) {
            if ($strategy->getName() == $name) {
                return $strategy;
            }
        }

        throw new Exception("Pricing Strategy '$name' not found");
    }
}

Lastly, we can refactor the code in question and reduce it to just 6 lines of code that don't require any ifs, switchs, ands (or buts):

$factory = new PricingStrategyFactory();
$pricing = $factory->find('motor');
$json = array(
    'total' => $pricing->calculatePrice(),
    "{$pricing->getName()}_option_1" => $pricing->getOption()
);

The getName method is used to generate the unique JSON array key that your response is expecting. The calculatePrice method becomes a black box that encapsulates the algorithm, so the rest of your code base doesn't need to know it.

You'll also notice that the PricingStrategy interface isn't referenced any place else but the definition of the interface, and the ProductPricingStrategy class. In the short code example above you won't see the benefit of the interface. When you need to pass this pricing strategy object around, you'll see the benefit.

First, let's pretend we have a fictional MVC framework, and we've created a "controller" class called "ProductPricesController". The MVC framework routes GET requests for /product_prices/calculate?type=ABC to the ProductPricesController#calculate method:

class ProductPricesController extends Controller
{
    // GET: /product_prices/calculate?type=motor

    public function calculate() {
        $type = $_GET['type'];
        $factory = new PricingStrategyFactory();
        $pricing = $factory->find($type);
        $json = $this->getPriceJson($pricing);

        echo json_encode($json);
    }

    private function getPriceJson(PricingStrategy $pricing) {
        return array(
            'total' => $pricing->calculatePrice(),
            "{$pricing->getName()}_option_1" => $pricing->getOption()
        );
    }
}

The getPriceJson method has a PHP Type Hint: PricingStrategy, which is the name of our interface. This helps the developer because it gives them information about what this method expects, and it helps the application because the interface becomes a "contract" between the controller and the pricing strategy so the two can interact in a predictable and modular manner.


问:
What licence should I choose for my project?
I originally thought of creative commons when while reading a book about wordpress (professional wordpress), I learned that I should also specify that the product is provided

... WITHOUT ANY WARRANTY; without even the
  implied warranty of MERCHANTABILITY or
  FITNESS FOR A PARTICULAR PURPOSE

and they recommend GNU GPL.  How do I write a license or select 1?

btw, what does MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE mean actually? Isn't without warranty enough?

答:
Have you considered the BSD license(s)? The simplest (relatively) form of it, known as "Simplified BSD License" or "FreeBSD License", is particularly fit for disclaiming any warranties and/or liabilities. It does not prevent commercialization or use of your code in commercial and/or proprietary software, but it makes sure you still are the copyright holder.

You can read it here. Depending on the laws of your country, it may be more suitable to your purposes than other, more complicated, licenses.


问:
is switch(this) antipattern or bad practice in Java for Enums?
At work I bumped into a problem to see how enums are growing and storing business logics. As they grew, the constructors grew a lot. At one point I found out instead of putting in let's say the tenth boolean parameter (and which already had various other parameters than boolean) into the constructor, and expand all the initializations with an extra parameter, I will make a new - yet not really used - construction for purpose of code readability.

Here is an example, so instead of:

```<code>public enum A {
  A1(true, true, false),
  A2(true, false, true),
  A3(false, false, false);

private A(boolean firstParam, boolean secondParam, boolean thirdParam){
    ... usual constructor ...
}

... getters
</code>```

So instead I did the following:

```<code>public enum A {
  A1,
  A2,
  A3;

... no need for special constructor

public boolean isFirstParam(){
  switch(this){
    case A1:
    case A2:
      return true;
    default:
      return false;
  }
}

public boolean isSecondParam(){
  switch(this){
    case A1:
      return true;
    default:
      return false;
  }
}

public boolean isThirdParam(){
  switch(this){
    case A2:
      return true;
    default:
      return false;
  }
}
</code>```

So far whoever used it likes it. But some collegues who were unaware of it had bad reactions:

Sonar was unhappy to see the switch(this) statement.

They didn't like the concept itself.

My question is: is there a real reason why I shouldn't use it? It is way more maintainable when you have complex enums. I do believe I didn't use anything special, just switching over enum, just in a special place. Am I right?

答:
The other alternative is overriding methods per instance:

```<code>public enum A {
  A1{
    @Override public boolean isFirstParam(){ return true; }
    @Override public boolean isSecondParam(){ return true; }
    @Override public boolean isThirdParam(){ return false; }
  },
  A2{
    @Override public boolean isFirstParam(){ return true; }
    @Override public boolean isSecondParam(){ return false; }
    @Override public boolean isThirdParam(){ return false; }
  },
  A3{
    @Override public boolean isFirstParam(){ return false; }
    @Override public boolean isSecondParam(){ return false; }
    @Override public boolean isThirdParam(){ return false; }
  };

  public abstract boolean isFirstParam();
  public abstract boolean isSecondParam();
  public abstract boolean isThirdParam();
}
</code>```

https://docs.oracle.com/javase/8/docs/technotes/guides/language/enums.html has this to say:

The idea of adding behavior to enum constants can be taken one step
  further. You can give each enum constant a different behavior for some
  method. One way to do this by switching on the enumeration constant.
  Here is an example with an enum whose constants represent the four
  basic arithmetic operations, and whose eval method performs the
  operation:

```<code>public enum Operation {
    PLUS, MINUS, TIMES, DIVIDE;

    // Do arithmetic op represented by this constant
    double eval(double x, double y){
        switch(this) {
            case PLUS:   return x + y;
            case MINUS:  return x - y;
            case TIMES:  return x * y;
            case DIVIDE: return x / y;
        }
        throw new AssertionError("Unknown op: " + this);
    }
}
</code>```

This works fine, but it will not compile without the throw statement,
  which is not terribly pretty. Worse, you must remember to add a new
  case to the switch statement each time you add a new constant to
  Operation. If you forget, the eval method with fail, executing the
  aforementioned throw statement

There is another way give each enum constant a different behavior for
  some method that avoids these problems. You can declare the method
  abstract in the enum type and override it with a concrete method in
  each constant. Such methods are known as constant-specific methods.
  Here is the previous example redone using this technique:

```<code>public enum Operation {
  PLUS   { double eval(double x, double y) { return x + y; } },
  MINUS  { double eval(double x, double y) { return x - y; } },
  TIMES  { double eval(double x, double y) { return x * y; } },
  DIVIDE { double eval(double x, double y) { return x / y; } };

  // Do arithmetic op represented by this constant
  abstract double eval(double x, double y);
}
</code>```

Personally I don't mind throwing an exception and explicitly handling all posibilities, except if the switch would be located in the enum itself.
The IDE gives me a warning (I can even configure it to turn it into an error so it won't compile) when you don't handle all cases.
If you keep your projects warning free, which I try to do, you will immidiently know which files need their switch statements updated.

Body:
The other alternative is overriding methods per instance:

public enum A {
  A1{
    @Override public boolean isFirstParam(){ return true; }
    @Override public boolean isSecondParam(){ return true; }
    @Override public boolean isThirdParam(){ return false; }
  },
  A2{
    @Override public boolean isFirstParam(){ return true; }
    @Override public boolean isSecondParam(){ return false; }
    @Override public boolean isThirdParam(){ return false; }
  },
  A3{
    @Override public boolean isFirstParam(){ return false; }
    @Override public boolean isSecondParam(){ return false; }
    @Override public boolean isThirdParam(){ return false; }
  };

  public abstract boolean isFirstParam();
  public abstract boolean isSecondParam();
  public abstract boolean isThirdParam();
}

https://docs.oracle.com/javase/8/docs/technotes/guides/language/enums.html has this to say:

The idea of adding behavior to enum constants can be taken one step
  further. You can give each enum constant a different behavior for some
  method. One way to do this by switching on the enumeration constant.
  Here is an example with an enum whose constants represent the four
  basic arithmetic operations, and whose eval method performs the
  operation:

public enum Operation {
    PLUS, MINUS, TIMES, DIVIDE;

    // Do arithmetic op represented by this constant
    double eval(double x, double y){
        switch(this) {
            case PLUS:   return x + y;
            case MINUS:  return x - y;
            case TIMES:  return x * y;
            case DIVIDE: return x / y;
        }
        throw new AssertionError("Unknown op: " + this);
    }
}

This works fine, but it will not compile without the throw statement,
  which is not terribly pretty. Worse, you must remember to add a new
  case to the switch statement each time you add a new constant to
  Operation. If you forget, the eval method with fail, executing the
  aforementioned throw statement

There is another way give each enum constant a different behavior for
  some method that avoids these problems. You can declare the method
  abstract in the enum type and override it with a concrete method in
  each constant. Such methods are known as constant-specific methods.
  Here is the previous example redone using this technique:

public enum Operation {
  PLUS   { double eval(double x, double y) { return x + y; } },
  MINUS  { double eval(double x, double y) { return x - y; } },
  TIMES  { double eval(double x, double y) { return x * y; } },
  DIVIDE { double eval(double x, double y) { return x / y; } };

  // Do arithmetic op represented by this constant
  abstract double eval(double x, double y);
}

Personally I don't mind throwing an exception and explicitly handling all posibilities, except if the switch would be located in the enum itself.
The IDE gives me a warning (I can even configure it to turn it into an error so it won't compile) when you don't handle all cases.
If you keep your projects warning free, which I try to do, you will immidiently know which files need their switch statements updated.


问:
my software model has some kind of cyclic dependency
I need a recommendation about my software model.

I think it is not that good, since there is some kind of cyclic dependency.

I have an OSGI bundle under Kura application framework, here are the classes:

Main class: the entry point of the bundle

TwoWaySerialComm: for serial communication with an Arduino device

SerialReader: responsible for reading from the serial port the data coming from the Arduino and then it sends the received data to the cloud using KURA service DataService.

```<code>class Main {
    public static DataService m_dataService;//KURA service to send information to the cloud via MQTT

    protected void activate(ComponentContext componentContext) {
    serialCom = new TwoWaySerialComm();//responsible for serial communication
      serialCom.connect("/dev/ttyUSB0");
    }
}

class TwoWaySerialComm {
    void connect(String portName) {
        //code omitted
        in = serialPort.getInputStream();
        //add event listener to read data from the serial port
        serialPort.addEventListener(new SerialReader(in));
        //code omitted
    }
}

public class SerialReader  implements SerialPortEventListener  {
    public void serialEvent(SerialPortEvent arg0) {

        //code for serial port reading omitted

        //the data obtained from the serial is sent to the
        //cloud via MQTT using the KURA service DataService as the following:
        Main.m_dataService.publish();
    }
}
</code>```

It is a bad modelling, if so how can I fix it?

答:
This seems like a problematic design. If a class can't stand on its own, it effectively becomes part of an unintended meta-Frankenstein class along with its hard dependencies. In this case, Main, TwoWaySerialComm, and SerialReader are effectively one class, maybe MainTwoWaySerialCommSerialReader.

I can see a couple ways around it.

If Main requires a reference to the DataService, share that reference as a parameter to TwoWaySerialComm and ultimately SerialReader. Don't expose it as a public member.

```<code>class Main {

    private static DataService m_dataService;

    protected void activate(ComponentContext componentContext) {
      serialCom = new TwoWaySerialComm();
      serialCom.connect("/dev/ttyUSB0", m_dataService);
    }
}

class TwoWaySerialComm{
    void connect (String portName, DataService service) {
       in = serialPort.getInputStream();
       serialPort.addEventListener(new SerialReader(in, service));
    }
}

public class SerialReader implements SerialPortEventListener {

    private Stream in;
    private DataService service;

    SerialReader (Stream in, DataService service) {
        this.in = in;
        this.service = service;
    }

    public void serialEvent(SerialPortEvent arg0) {
        this.service.publish();
    }
}
</code>```

Now, both TwoWaySerialComm and SerialReader can be used in other contexts. They don't require Main.

Another option is to push responsibility for the DataService closer to where it's used. If it's feasible, the SerialReader could "own" it.

```<code>class Main {
    protected void activate(ComponentContext componentContext) {
      serialCom = new TwoWaySerialComm();
      serialCom.connect("/dev/ttyUSB0");
    }
}

class TwoWaySerialComm{
    void connect (String portName) {
       in = serialPort.getInputStream();
       serialPort.addEventListener(new SerialReader(in));
    }
}

public class SerialReader implements SerialPortEventListener {

    private Stream in;
    private DataService service;

    SerialReader (Stream in) {
        this.in = in;
        // Not sure if this is possible.
        // If it is, it reduces the need to juggle the DataService
        // reference between classes.
        this.service = ResolveDataServiceSomehow();
    }

    public void serialEvent(SerialPortEvent arg0) {
        this.service.publish();
    }
}
</code>```

Body:
This seems like a problematic design. If a class can't stand on its own, it effectively becomes part of an unintended meta-Frankenstein class along with its hard dependencies. In this case, Main, TwoWaySerialComm, and SerialReader are effectively one class, maybe MainTwoWaySerialCommSerialReader.

I can see a couple ways around it.

If Main requires a reference to the DataService, share that reference as a parameter to TwoWaySerialComm and ultimately SerialReader. Don't expose it as a public member.

class Main {

    private static DataService m_dataService;

    protected void activate(ComponentContext componentContext) {
      serialCom = new TwoWaySerialComm();
      serialCom.connect("/dev/ttyUSB0", m_dataService);
    }
}

class TwoWaySerialComm{
    void connect (String portName, DataService service) {
       in = serialPort.getInputStream();
       serialPort.addEventListener(new SerialReader(in, service));
    }
}

public class SerialReader implements SerialPortEventListener {

    private Stream in;
    private DataService service;

    SerialReader (Stream in, DataService service) {
        this.in = in;
        this.service = service;
    }

    public void serialEvent(SerialPortEvent arg0) {
        this.service.publish();
    }
}

Now, both TwoWaySerialComm and SerialReader can be used in other contexts. They don't require Main.

Another option is to push responsibility for the DataService closer to where it's used. If it's feasible, the SerialReader could "own" it.

class Main {
    protected void activate(ComponentContext componentContext) {
      serialCom = new TwoWaySerialComm();
      serialCom.connect("/dev/ttyUSB0");
    }
}

class TwoWaySerialComm{
    void connect (String portName) {
       in = serialPort.getInputStream();
       serialPort.addEventListener(new SerialReader(in));
    }
}

public class SerialReader implements SerialPortEventListener {

    private Stream in;
    private DataService service;

    SerialReader (Stream in) {
        this.in = in;
        // Not sure if this is possible.
        // If it is, it reduces the need to juggle the DataService
        // reference between classes.
        this.service = ResolveDataServiceSomehow();
    }

    public void serialEvent(SerialPortEvent arg0) {
        this.service.publish();
    }
}


答:
Why? Well, think of it this way - you're happy with this situation because you're the one putting it in there, so you already know what @Link means. Your colleagues probably do not. This is the pain point of abstractions.

Imagine you come across a new page someone else has created and all it has is @Page_7 at the top. You'd be annoyed that so much information about the creation and layout of the page had been abstracted (and I'd agree) but this extreme example shows what the problem is - in order to use such abstractions you all need to know they are being used, and understand where and how much they will be used. Maybe if you came across @@header@@ and didn't know the tooling used to turn that into code or even where to find the raw code, then you'd be complaining too.

I've seen too much code that disappears into a black box and pops out the other end with no way of knowing what happened in the middle (which is where it usually goes wrong).

Now this may not be the case with your team and they just want to see raw HTML. If that's the way the team wants it though, that's the way it has to be. You cannot arbitrarily do something different if they don't use such techniques. Not only is that not good teamwork, but it introduces artefacts that they will not understand because they don't use them.

Title: Resistance to abstraction

Body:
I am on an ASP.NET MVC project where we use Razor to define pages. One thing I like to do is to use Razor's @helper to DRY up pretty much any duplication in HTML (i.e. formalize even small UI patterns). To give an example. At the top of the page there are 3 "quick links" buttons at the top of the page, titled A, B and C. That take user to pages A, B and C respectively. I could type out three times:

A

but I do:

@Link("A", "a")

Please note, my question is not weather this approach is right or wrong. The question is not about benefits of abstractions for maintenance. I have a very specific question here.

What I am often faced with is this desire (not an argument) to "see raw HTML". I want to understand where does this desire to see "raw HTML" comes from. People often say "maybe it is the anguish back from the days of WebForms where all that abstraction was painful".

Why do people yearn to grind through noise to get to the relevant data?


答:
HTML is a perfect fit for abstractions, and that is why there are many templating systems. The problem with your example is maybe that you are hiding too much information: target and class attributes are implicitely defined, and @Link, as a name, is too generic. If the link is a quick-link, call it @QuickLink.

If your team already use Razor, it seems that learning and maintenance costs have been deemed acceptable by your colleagues, so I doubt they are strongly opposed to the approach in principle.

I am afraid you would have to ask more questions to understand the pain that is felt by your colleagues. Ask them how they would rewrite your example and what they would do to mitigate the problem of having duplicate code. I don't use this particular technology, but how difficult is to debug? How difficult is it to run a test and see the generated HTML?

Title: Resistance to abstraction


问:
Data transfer between "main" site and secured virtual subsite
I am currently working on a C# ASP.Net 3.5 website I wrote some years ago which consists of a "main" public site, and a sub-site which is our customer management application, using forms-based authentication. The sub-site is set up as a virtual folder in IIS and though it's a subfolder of "main", it functions as a separate web app which handles CRUD access to our customer database and is only accessible by our staff.

The main site currently includes a form for new leads to fill in, which generates an email to our sales staff so they can contact them and convince them to become customers. If that process is successful, the staff manually enter the information from the email into the database.

Not surprisingly, I now have a new requirement to feed the data from the new lead form directly into the database so staff can just check a box for instance to turn the lead into a customer.

My question therefore is how to go about doing this? Possible options I've thought of:

Move the new lead form into the customer database subsite (with authentication turned off).

Add database handling code to the main site. (No, not seriously considering this duplication of effort! :)

Design some mechanism (via REST?) so a webpage outside the customer database subsite can feed data into the customer database

How to organise the code for this situation, preferably with extensibility in mind, and particularly are there any options I haven't thought of?

答:
I would suggest Option #4: Create a class library encapsulating this shared functionality that both sites could add as a Reference in Visual Studio.

This new project would be a Class Library in Visual Studio. It would have Domain Models that enforce the business logic of creating a new lead, and it would have Repository classes doing the actual INSERTs, UPDATEs and DELETEs from the Database, as well as fetching the data.

While people tend to immediately gravitate towards REST services, because your two sites are both using the .NET framework a shared class library will be easier to build, deploy, and maintain over the long run. Additionally, you won't need to incur the additional overhead of making HTTP requests and handling the responses, which will make both applications run faster for these operations.

I like to keep Martin Fowler's advice in mind regarding Microservices (which applies to Service Oriented Architecture in general):

First Law of Distributed Object Design: "don't distribute your objects"

Creating a REST service is just another way of "distributing your objects" since these objects must exist in both applications, and also must be serialized and deserialized for transit over a network.

He goes on to justify this "law":

My objection to the notion of distributed objects was although you can encapsulate many things behind object boundaries, you can't encapsulate the remote/in-process distinction. An in-process function call is fast and always succeeds (in that any exceptions are due to the application, not due to the mere fact of making the call). Remote calls, however, are orders of magnitude slower, and there's always a chance that the call will fail due to a failure in the remote process or the connection.

(Emphasis, mine)

Why deal with a fickle network connection and web application stack when you can just make in-process calls to the same database? What you are really trying to avoid is duplicated code. Creating a shared class library for your two .NET projects achieves this.

Multiple Applications, Different Technology Stacks

If you had a public facing application written in Java, and your back-office application written in C# then you would have a good case for one of two solutions:

Create stored procedures in the same database that are called by both applications

Create a REST service called by both applications

Even then, I would go with stored procedures first, before creating a web service. If your public and back-office applications need to handle "leads" and you've got an Android and iOS app doing the same thing then I would create a REST or web service. Web services really start to shine in multi platform environments where one or more platforms are "client side" (i.e. in a browser, mobile app, or a third party company needs to use this functionality).

If it's just you and your company's web sites, go with a class library first, then stored procedures, and as a last resort create a web service.


答:
Yes, the excessive knowledge of other classes and the corresponding tight coupling is bad.

Good news! It's easily resolved with dependency inversion.

The key flaw is that SerialReader knows that Main has its DataService dependency.  It doesn't need to know this, and shouldn't.  Instead it should be constructed with a DataService.  This is called dependency inversion or dependency injection.

SerialReader.java:

```<code>public final class SerialReader  implements SerialPortEventListener {
    private final DataService dataService;

    public SerialReader(DataService dataService) {
        this.dataService = dataService;
    }

    public void serialEvent(SerialPortEvent arg0) {
        //code for serial port reading omitted

        //the data obtained from the serial is sent to the
        //cloud via MQTT using the KURA service DataService as the following:
        dataService.publish();
    }
}
</code>```

The same technique can be applied with even more flourish on TwoWaySerialComm as it can depend on the SerialPortEventListener interface instead of a specific class making it very loosely coupled.

TwoWaySerialComm.java

```<code>final class TwoWaySerialComm  {
    private final SerialPortEventListener serialPort;

    TwoWaySerialComm(SerialPortEventListener serialPort) {
        this.serialPort = serialPort;
    }

    void connect(String portName)  {
        //code omitted
        in = serialPort.getInputStream();
        //add event listener to read data from the serial port
        serialPort.addEventListener(new SerialReader(in));
        //code omitted
    }
}
</code>```

And the Main does its job which is, and should always be, restricted to wiring up dependencies and starting the system.

Main.java:

```<code>final class Main  {
    //KURA service to send information to the cloud via MQTT
    public static final DataService dataService;

    protected void activate(ComponentContext componentContext) {
        SerialReader serialReader = new SerialReader(dataService);
        TwoWaySerialComm serialCom = new TwoWaySerialComm(serialReader);//responsible for serial communication
        serialCom.connect("/dev/ttyUSB0");
    }
}
</code>```

You may notice I've renamed m_dataService to dataService.  The m_ is occasionally used in C++, but is considered bad style in Java.

Title: my software model has some kind of cyclic dependency

Body:
I need a recommendation about my software model.

I think it is not that good, since there is some kind of cyclic dependency.

I have an OSGI bundle under Kura application framework, here are the classes:

Main class: the entry point of the bundle

TwoWaySerialComm: for serial communication with an Arduino device

SerialReader: responsible for reading from the serial port the data coming from the Arduino and then it sends the received data to the cloud using KURA service DataService.

```<code>class Main {
    public static DataService m_dataService;//KURA service to send information to the cloud via MQTT

    protected void activate(ComponentContext componentContext) {
    serialCom = new TwoWaySerialComm();//responsible for serial communication
      serialCom.connect("/dev/ttyUSB0");
    }
}

class TwoWaySerialComm {
    void connect(String portName) {
        //code omitted
        in = serialPort.getInputStream();
        //add event listener to read data from the serial port
        serialPort.addEventListener(new SerialReader(in));
        //code omitted
    }
}

public class SerialReader  implements SerialPortEventListener  {
    public void serialEvent(SerialPortEvent arg0) {

        //code for serial port reading omitted

        //the data obtained from the serial is sent to the
        //cloud via MQTT using the KURA service DataService as the following:
        Main.m_dataService.publish();
    }
}
</code>```

It is a bad modelling, if so how can I fix it?

Body:
Yes, the excessive knowledge of other classes and the corresponding tight coupling is bad.

Good news! It's easily resolved with dependency inversion.

The key flaw is that SerialReader knows that Main has its DataService dependency.  It doesn't need to know this, and shouldn't.  Instead it should be constructed with a DataService.  This is called dependency inversion or dependency injection.

SerialReader.java:

public final class SerialReader  implements SerialPortEventListener {
    private final DataService dataService;

    public SerialReader(DataService dataService) {
        this.dataService = dataService;
    }

    public void serialEvent(SerialPortEvent arg0) {
        //code for serial port reading omitted

        //the data obtained from the serial is sent to the
        //cloud via MQTT using the KURA service DataService as the following:
        dataService.publish();
    }
}

The same technique can be applied with even more flourish on TwoWaySerialComm as it can depend on the SerialPortEventListener interface instead of a specific class making it very loosely coupled.

TwoWaySerialComm.java

final class TwoWaySerialComm  {
    private final SerialPortEventListener serialPort;

    TwoWaySerialComm(SerialPortEventListener serialPort) {
        this.serialPort = serialPort;
    }

    void connect(String portName)  {
        //code omitted
        in = serialPort.getInputStream();
        //add event listener to read data from the serial port
        serialPort.addEventListener(new SerialReader(in));
        //code omitted
    }
}

And the Main does its job which is, and should always be, restricted to wiring up dependencies and starting the system.

Main.java:

final class Main  {
    //KURA service to send information to the cloud via MQTT
    public static final DataService dataService;

    protected void activate(ComponentContext componentContext) {
        SerialReader serialReader = new SerialReader(dataService);
        TwoWaySerialComm serialCom = new TwoWaySerialComm(serialReader);//responsible for serial communication
        serialCom.connect("/dev/ttyUSB0");
    }
}

You may notice I've renamed m_dataService to dataService.  The m_ is occasionally used in C++, but is considered bad style in Java.


问:
Why is JSX good, when JSP scriptlets are bad?
React.js provides JSX as an XHTML-like syntax for constructing a tree of components and elements.  JSX compiles to Javascript, and instead of providing loops or conditionals in JSX proper, you use Javascript directly:

```<code><ul>
  {list.map((item) =>
    <li>{item}</li>
  )}
</ul>
</code>```

What I haven't been able to explain yet is, why is this considered good if analogous constructs are considered bad in JSP?

Something like this in JSP

```<code><ul>
   <% for (item in list) { %>
     <li>${item}</li>
   <% } %>
</ul>
</code>```

is considered a readability problem to be solved with tags like <c:forEach>.  The reasoning behind JSTL tags also seem like they could apply to JSX:

it's a little easier to read when you aren't toggling between XHTML-like syntax (angle brackets, nesting) and Java/Javascript (curlies, commas, parens)

when you have the full language and platform available for use inside the rendering function, there's less to discourage you from putting logic in that doesn't belong there.

The only reasons I can think of why JSX is different is:

in Java, you had an incentive to do the wrong thing - JSP would be hot-reloaded, so it was tempting to put code in JSPs to avoid a rebuild/restart cycle.  Maintainability was sacrificed for immediate productivity. Banishing scriptlets and limiting to a fixed set of template constructs was effectively a way of enforcing maintainability.  No such distortion exists in the JS world.

JSP and Java syntax is clunky with the extra <% ... %> to distinguish Java code from element generation, and with Java's native syntax lacking a foreach concept or first-class functions (until recently). The syntax penalty of using native Javascript for loops and conditionals in JSX is non-zero (in my opinion) but not as bad as JSP, and arguably not bad enough to warrant introducing JSX-specific elements for loops and conditionals.

Is there something else I'm missing?

答:
While I don't use JSX, based on your description, the job of the JSX fragment is to present the data, that is, it's a view component in the MVC parlance. The JSX fragment presumably doesn't know or care where the data came from which is what you want.

A well structured JSP page will just contain JSTL directives like you mention. JSTL directives just simplify your JSPs so they're not cluttered with fetching from scope, checking for null etc. It's surprising how much clutter this removes and it also encourages you to keep it decluttered.

Just like the JSX fragment; the only job of the JSP should be to figure out how to present the data it has received without worrying about where it came from.

In summary, whether your view is JSX or JSP, if you're doing it properly then your view will just present data.

As to why you might shift the presentation to the client instead of doing it on the server, this gives you more flexibilty. Your web site can get its data via web services (ReST for example) and be just another client. If you later decide that you want a native Android or iOS app, they can consume the same set of web services as your web site.


问:
Why is using 'final' on a class really so bad?
I am refactoring a PHP OOP legacy website.

I am so tempted to start using 'final' on classes to "make it explicit that the class is currently not extended by anything".  This might save lots of time if I come to a class and I am wondering if I can rename/delete/modify a protected property or method. If I really want to extend a class I can just remove the final keyword to unlock it for extending.

I.e If I come to a class that has no child classes I can record that knowledge by marking the class a final. The next time I come to it I would not have to re-search the codebase to see if it has children. Thus saving time during refactorings.

It all seems like a sensible time saving idea.... but I have often read that classes should only be made 'final' on rare/special occasions.

Maybe it screws up Mock object creation or has other side effects that I am not thinking of.

What am I missing?

答:
There is a nice article about "When to declare classes final". A few quotes from it:

TL;DR: Make your classes always final, if they implement an interface, and no other public methods are defined

Why do I have to use final?

Preventing massive inheritance chain of doom

Encouraging composition

Force the developer to think about user public API

Force the developer to shrink an object's public API

A final class can always be made extensible

extends breaks encapsulation

You don't need that flexibility

You are free to change the code

When to avoid final:

Final classes only work effectively under following assumptions:

There is an abstraction (interface) that the final class implements

All of the public API of the final class is part of that interface

If one of these two pre-conditions is missing, then you will likely reach a point in time when you will make the class extensible, as your code is not truly relying on abstractions.

P.S. Thanks to @ocramius for great reading!