答:
I think you are suffering from YAGNI in your design. Think about it like this - when would you ever interact with a clock and a seat in the same way? Answer: you wouldn't! You might name a clock, and name a seat, but you wouldn't sit on a clock, nor would you increment a seat. It doesn't make any sense.

Interfaces are for common behavior. For example, you might have an interface Named, which you would give to all implementations that have a Name. You might have an interface Timed, which might be given to all Events that occur at a specific time. Or you might have an interface Sittable, which would be implemented by Chair and Sofa.

If you really want to have an interface Interactable, you should either pass it something where the object itself can figure out what is doing the interaction, like Object[], or the object of what's being interacted with, such as Player.

Don't think about this sort of design in the beginning. Figure out what sort of interactions you are actually going to do, and figure out what the common behavior is going to be, and then design your interfaces at that level.

Response to comment:

when one interacts with a room, it uses that object (e.g. a Sofa or a Clock)'s interaction, how can I tell which it is with no prior knowledge?

This is what I was saying in the last paragraph. You put the behavior of the room in the code for the object itself, e.g. (Java syntax, but C# is very similar)

```<code>public class Bed implements Interactable {
  @Override
  void interact(World world, Player player) {
    player.addRest(10);
    world.advanceTime(8, TimeUnit.HOUR);
  }
}
</code>```

Title: "Correct" way to use inheritance

Body:
Within a small project, a class Storage is meant to store any type of Item. Now, an Item has a String name, and an interaction. For example, a clock item might implement the interaction increment(int num), whereas a seat might implement sit(bool true).

Should I be simply writing classes for Item, Clock and Seat and letting Seat and Clock inherit from Item? Obviously the interaction they use varies, so short of writing every possible Item's interaction as a virtual method in Item I'm not sure how to deal with all the specific interaction types.

At the moment, I'm finding the Item and then using using conditionals to use the correct behavior on interaction, but that seems sort of roundabout and not so great.

Is there a better way to do this?

Body:
I think you are suffering from YAGNI in your design. Think about it like this - when would you ever interact with a clock and a seat in the same way? Answer: you wouldn't! You might name a clock, and name a seat, but you wouldn't sit on a clock, nor would you increment a seat. It doesn't make any sense.

Interfaces are for common behavior. For example, you might have an interface Named, which you would give to all implementations that have a Name. You might have an interface Timed, which might be given to all Events that occur at a specific time. Or you might have an interface Sittable, which would be implemented by Chair and Sofa.

If you really want to have an interface Interactable, you should either pass it something where the object itself can figure out what is doing the interaction, like Object[], or the object of what's being interacted with, such as Player.

Don't think about this sort of design in the beginning. Figure out what sort of interactions you are actually going to do, and figure out what the common behavior is going to be, and then design your interfaces at that level.

Response to comment:

when one interacts with a room, it uses that object (e.g. a Sofa or a Clock)'s interaction, how can I tell which it is with no prior knowledge?

This is what I was saying in the last paragraph. You put the behavior of the room in the code for the object itself, e.g. (Java syntax, but C# is very similar)

public class Bed implements Interactable {
  @Override
  void interact(World world, Player player) {
    player.addRest(10);
    world.advanceTime(8, TimeUnit.HOUR);
  }
}


问:
Why is object-level privacy difficult to use as a paradigm, and why is it desirable?
I have heard a prominent language designer remark that no language today enforces real object privacy, and we are still unsure whether it is possible in practice to design a language that does.

Without trying to read this particular person's mind, this piqued my interest. There are, I think, two distinct concepts at work here:

Languages with class-level privacy almost always provide ways to work-around it - for example with introspection. Are these workarounds necessary, in that their absence would make certain problems much harder to solve in the language, and if so, doesn't that indicate that the privacy paradigm is flawed? In other words, do people (ab)use these mechanisms when they are provided, and why?

Class-level privacy is not object-level privacy (an object has access to private state of other objects if they are of the same class), and we don't know how to do the latter. But why would we want to?

答:
If class Foo accepts references to objects of its type from outside code and uses private members thereof, then outside code will need to use references of type Foo or one of its subtypes.  If Foo didn't need to use private members of its own type, but it implemented an interface which included all the members it did need to use, then it would be possible for outside code to use that interface type instead of Foo, allowing such code to work with other implementations of that interface.

It would be possible for Foo's methods to accept parameters of the interface type even if the language didn't enforce object-level privacy, but it wouldn't be able to access any of the private members of the objects identified by those interface references.  Nonetheless, the ability of Foo's methods to make use of private members of passed-in references may serve to discourage the use of more general types as message parameters.

ContentLicense: CC BY-SA 3.0


问:
Names for the two types of AI (in my eyes)?
In my head, AI attempts get sorted into two categories. I'm wondering if the distinction is present in reality or just my imagination. If this it's real, I'd like to know of any terms for them. The two types are as follows.

The first (in an arbitrary order) is mostly seen in modern times. It consist of simulating the hardware of the brain, like artificial neural networks do. This is imitating the brain on a very low level, sort of like doing a physics simulation at the atom level, when you are trying to simulate, say, a ball rolling down a hill. It works great but it doesn't provide much insight about the nature of thought. The algorithm does not have to be a direct simulation of the brain, but it will always be relatively simple, removed from any high-level representation of cognitive processes, and the complexity of it's behavior will come from the data fed into it. To put it bluntly, a "simple" learning algorithm + a ton of data.

I encountered the second type only in older writings about AI. I'd say it's a semantic approach, to use quite a loaded word. An attempt is made to describe cognitive activity, usually all of it (aiming for a general/complete AI), on a high level. Words like "problem", "frame", "context", "agent", "rule" and the sort give it away. The task is to design an algorithm for thought, or rather to algorithmically describe thinking. I have not seen this approach yielding much results. Most AI programs nowadays use the first approach, at least that's what my confirmation bias says.

There are, of course, two competing theories of the brain, parallel to these two approaches, at least on a shallow level. One is evolutionary biology, mirroring the "semantic" variety. Not so much the evolutionary part, rather the idea that the brain is composed of mostly static modules which implement various functions of thought. I don't know of a name for the opposing view, but it's the belief that brain is a very efficient learning machine, with only a couple basic, tiny, modules for learning being built-in, and the rest acquired along the way. I learned of this distionction from this article: http://lesswrong.com/lw/md2/the_brain_as_a_universal_learning_machine/.

答:
You might consider that the first is related to machine learning, but the second is symbolic Artificial Intelligence.

J.Pitrat's blog has an entry: the future of AI is the Good Old Fashioned AI explaining why symbolic AI could still be relevant.

BTW, you might be interested by Artificial General Intelligence, as a research domain.

See also this & that answers.

Notice that AI experts are currently disagreeing on what AI really is...


问:
How do you use exit status code?
When the program run successfully, usually the program will return 0 status. If there any problems, the we can return value other than 0 at exit. With Exceptions, (as long as the problem is not undefined behaviour), we can return 0 value even though program is unsuccessfully finished.

My questions is:

Is the status code used to identify what problem that occured?
Maybe for tracking bugs or documentation purpose?

Is exception have to return status code other than 0 or is it
bad to return non 0 exit code?

How do you decide which status code to be returned? Can I return
the same status code for different errors?

Generally, the question is:

How do you use exit status code?

答:
You use exit codes when the application will be ran by a seperate process, which can make decisions based upon the results.

What exit code you should return under any specific circumstances, will be between you and your caller.   I typically use exit codes for scheduled jobs/task and limit the return to sucess and failure.  Really it's all up to you.

Title: How do you use exit status code?


问:
What is an example of a good SMART objective for a programmer?
Following on from this question, I wondered if folk might be able to suggest some samples of what might be considered a "good" objective in a periodic review cycle for a programmer?

Let's define SMART from the most popular definitions in the Wikipedia entry:

Specific

Measurable

Attainable

Relevant

Time-bound

答:
I have come to realize that SMART goals are best used when people have a deficiency they need to correct, and are not so good for times you want people to grow or go from good to great. If someone is not doing timesheets, for example, and this is hurting the company because you sometimes have to delay invoicing, you could have a smart goal like "over the next 6 weeks, at least 5 weeks' timesheets will be completed by 10am of the next Monday morning." 6 weeks later you have a true or false; the developer made it or missed it. Either the new habit is in place or you get to decide if you want to still employ someone who doesn't mind delaying your invoicing. Works for people who have other bad habits too: "over the next two weeks, at least 75% of your checkins will have a checkin comment that follows the checkin guidelines (link to internal document)." Again you have a nice crisp did/didn't at the end of that short time.

Where I find these constructs less helpful is when the timeframe lengthens, when the achievement you want is fuzzy (learn a language, be more helpful), or when it's ok if the goal is not achieved (you may value certifications, but if someone failed their test you probably wouldn't take disciplinary action.) Suddenly all the benefits of the smart goal fall away. Don't try to use them for anything other than corrective actions, and they're easy to write, they help the developer get up to the expected level, and they're easy to test for when the time's up. Having trouble writing them means they're not the right tool for this goal.

ContentLicense: CC BY-SA 2.5


问:
Is enum order sensitivity an antipattern?
Is it an anti-pattern to depend on a particular order of an enum's instance declarations? For example, consider:

```<code>public enum CompassPoint {
    North,
    East,
    South,
    West;
}
</code>```

These points are in clockwise order. Is there a good reason to not have code rely on this fact? More specifically, is it "OK" to rely on this code:

```<code> CompassPoint from;
 int toRightIndex = (from.ordinal() + 1) % CompassPoint.values();
 CompassPoint toRight = CompassPoint.values()[toRightIndex];
</code>```

"OK" here is "best practice", including avoiding a time bomb if someone innocently added instances for the quarter points, which may (or may not) break the intention of the meaning of "to right".

If "not OK", is it less "not OK" if such code is restricted to being internal to the enum class?

答:
It makes sense to place enum into some logical order if for no other reason than for the sake of making sense of them. For example, would you have not put an enum of months with February after October? (rhetorical question).

In several langauges enums can be treated as having an order, much like the example you provide. For that reason it makes great sense to put them in logical or perhaps more correctly 'real world order'.

From the example you provide, not all cultures necessary take things in 'clockwise' order, in fact some cultures inherently use 'counter-clockwise' ordering. In these cultures you will find enums which represent things compass direction to be in 'counter-clockwise' order. Something such as months which do not have a clockwise/counterclockwise idea are still found in ordinal order.

Another consideration about order comes when you consider sorting. If you would sort North before East then that should be the order used to fall inline with default sorting algorithms that might sort things using the enum as the key.

When you write code you should take into consideration your own expectations or those who might use your code. If you know and expect your enums to follow clockwise order, then you should use that as best practice. If you are writing code to be used by people who typically use counterclockwise order then you may want to order them that way instead. It might also be argued that since most cultures use clockwise rotation then that is what you should use and rely on.

No matter what you do, some sense of order should be maintained and should be kept consistent across all your code, if you use clockwise, then use it everywhere. I wouldn't, however, do something like enum { North, South, East, West } as that has no typical ordering.


答:
I think you've pretty much answered your own question :)

The major reason not to rely on the ordinal in code external to the enum, is dealing with change. Like you've pointed out, adding a NorthEast compass point might alter the meaning of your 'toRightIndex' calculation.
If you've written code that relies on the ordinal, that will probably need to change. So it makes sense not to rely on the ordinal outside the enum.

That said, I can't see any practical drawback in using the ordinal in a method internal to the enum - provided that to the
people maintaining and using the code, the ordinal represents an easily-understood order that makes sense in the real world.

A bit of advice from the javadocs for Enum:

public final int ordinal()

  Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero).
  Most programmers will have no use for this method.
  It is designed for use by sophisticated enum-based data structures, such as EnumSet and EnumMap.

Title: Is enum order sensitivity an antipattern?

Body:
Is it an anti-pattern to depend on a particular order of an enum's instance declarations? For example, consider:

```<code>public enum CompassPoint {
    North,
    East,
    South,
    West;
}
</code>```

These points are in clockwise order. Is there a good reason to not have code rely on this fact? More specifically, is it "OK" to rely on this code:

```<code> CompassPoint from;
 int toRightIndex = (from.ordinal() + 1) % CompassPoint.values();
 CompassPoint toRight = CompassPoint.values()[toRightIndex];
</code>```

"OK" here is "best practice", including avoiding a time bomb if someone innocently added instances for the quarter points, which may (or may not) break the intention of the meaning of "to right".

If "not OK", is it less "not OK" if such code is restricted to being internal to the enum class?


答:
I'd also say, you mostly answered the question by your own. I wouldn't implement it that way because it is brittle.

When having that code as part of the enum class itself, it is certainly better because the problem is isolated to the implementation detail of the enum. For the problem at hand I think that solution would be 'good enough' and therefore acceptable.

When assuming that the enum will be used frequently and is likely to be extended in the future, I'd make use of the advanced Java enum features like fields and methods:

```<code>    public enum CompassDirection {
    NORTH(0),
    EAST(90),
    SOUTH(180),
    WEST(270);

    private final double degreesFromNorth;

    CompassDirection(double degreesFromNorth) {
        this.degreesFromNorth = degreesFromNorth;
    }

    public CompassDirection directionToRight(){
        directionForDegreesFromNorth(degreesFromNorth + 90);
    }

    public CompassDirection directionToLeft(){
        directionForDegreesFromNorth(degreesFromNorth - 90);
    }

    public CompassDirection directionForDegreesFromNorth(double degreesFromNorth){
        double normalizedDegrees = Math.floorMod(degreesFromNorth, 360);
        for(CompassDirection direction : CompassDirection.values()){
            if(direction.degreesFromNorth == normalizedDegrees){
                return direction;
            }
        }

        throw new Exception("No matching direction could be found");
    }
}
</code>```

Java enums are really powerful and I must say I miss them badly when programming C#.

Body:
I'd also say, you mostly answered the question by your own. I wouldn't implement it that way because it is brittle.

When having that code as part of the enum class itself, it is certainly better because the problem is isolated to the implementation detail of the enum. For the problem at hand I think that solution would be 'good enough' and therefore acceptable.

When assuming that the enum will be used frequently and is likely to be extended in the future, I'd make use of the advanced Java enum features like fields and methods:

    public enum CompassDirection {
    NORTH(0),
    EAST(90),
    SOUTH(180),
    WEST(270);

    private final double degreesFromNorth;

    CompassDirection(double degreesFromNorth) {
        this.degreesFromNorth = degreesFromNorth;
    }

    public CompassDirection directionToRight(){
        directionForDegreesFromNorth(degreesFromNorth + 90);
    }

    public CompassDirection directionToLeft(){
        directionForDegreesFromNorth(degreesFromNorth - 90);
    }

    public CompassDirection directionForDegreesFromNorth(double degreesFromNorth){
        double normalizedDegrees = Math.floorMod(degreesFromNorth, 360);
        for(CompassDirection direction : CompassDirection.values()){
            if(direction.degreesFromNorth == normalizedDegrees){
                return direction;
            }
        }

        throw new Exception("No matching direction could be found");
    }
}

Java enums are really powerful and I must say I miss them badly when programming C#.


问:
Best practice for a REST-ful API where objects would naturally have a "/" in their identifier
I am designing a REST api for a document management system. To make the API more natural, I thought about using the natural identifier for a file, which is it's path (usually having forward slashes "/" in it), and not something like an artificial id such as a UUID.

Naturally, a user would identify a file by it's path:

```<code>/path/to/file.txt
</code>```

Unfortunately, this clashes with common, good API design.

This would work:

```<code>Retrieving a file: GET /api/v1/files/<path/to/file.txt>
</code>```

However, other methods you would like to have, will become a bit problematic:

```<code>Retrieving a file list of a folder: GET /api/v1/folders/<path/to/folder>/files
</code>```

My thoughts so far:

avoid unique identifiers with "/" in it entirely, and use an artificial UUID (such as Alfresco is using NodeId / NodeRefs). This would add another layer of abstraction to it, where a unique id is just not very natural from a business domain perspective

don't use the identifier in the url path but in a parameter (against good API design patterns)

(requesting the API users to replace the / with another character is of course also not an option)

Of course, files and folders as we know it from a file system, are naturally identified by it's path. In that particular case, one could argue that if someone wants to use the path as the identifier, than the correct way for doing:

```<code>Retrieving a file: GET /api/v1/files/<path/to/file.txt>
</code>```

would actually be:

```<code>Retrieving a file: GET /api/v1/folders/<path>/folders/<to>/files/<file.txt>
</code>```

if we want to be really correct here.

Update: I want to ask the community about best practices and experiences here - especially when Dropbox and Google Drive both use two different approaches (see first answer and comments below): DropBox is using the path while Google Drive is using IDs.

答:
Forget about files for a moment.

You have an API, and at some point you need to insert identifiers specific to your application. Since your application isn't primarily interested in the features of the API, and because these identifiers are determined without even knowing about the API, you need to be able to translate an arbitrary identifier into something that the API can handle.

There is a standard mechanism for this, which is percent encoding. It handles all these pesky cases like identifiers containing slashes, less than and greater.  For example, on my Mac, /"what</do">you think/"about>>this is a perfectly valid path with the three path components "what<, do">you think, and "about>>this. Percent encoding has no problem with this.


问:
Do I need to use an interface when only one class will ever implement it?
Isn't the whole point of an interface that multiple classes adhere to a set of rules and implementations?</p>

答:
No, you don't need them, and I consider it an anti-pattern to automatically make interfaces for every class reference.

There is a real cost to making Foo/FooImpl for everything.  The IDE may create the interface/implementation for free, but when you're navigating code, you have the extra cognitive load from F3/F12 on foo.doSomething() taking you to the interface signature and not the actual implementation you want.  Plus you have the clutter of two files instead of one for everything.

So you should only do it when you actually need it for something.

Now addressing the counterarguments:

I need interfaces for Dependency injection frameworks

Interfaces to support frameworks are legacy.  In Java, interfaces used to be a requirement for dynamic proxies, pre-CGLIB.  Today, you usually don't need it.  It's considered progress and a boon for developer productivity that you don't need them anymore in EJB3, Spring etc.

I need mocks for unit testing

If you write your own mocks and have two actual implementations, then an interface is appropriate.  We probably wouldn't be having this discussion in the first place if your codebase had both a FooImpl and a TestFoo.

But if you're using a mocking framework like Moq, EasyMock, or Mockito, you can mock classes and you don't need interfaces.  It's analogous to setting foo.method = mockImplementation in a dynamic language where methods can be assigned.

We need interfaces to follow Dependency Inversion Principle (DIP)

DIP says you build to depend on contracts (interfaces) and not implementations. But a class is already a contract and an abstraction.  That's what the public/private keywords are for.  In university, the canonical example was something like a Matrix or Polynomial class -- consumers have a public API to create matrixes, add them etc. but aren't allowed to care if the matrix is implemented in sparse or dense form.  There was no IMatrix or MatrixImpl required to prove that point.

Also, DIP is often over-applied at every class/method call level, not only at major module boundaries.  A sign that you're over-applying DIP is that your interface and implementation change in lock-step such that you have to touch two files to make a change instead of one. If DIP is applied appropriately, it means that  your interface shouldn't have to change often.  Also, another sign is that your interface only has one real consumer (its own application).  Different story if you're building a class library for consumption in many different apps.

This is a corollary to Uncle Bob Martin's point about mocking -- you should only need to mock at major architectural boundaries.  In a webapp the HTTP and DB access are the major boundaries.  All the class/method calls in between are not. Same goes for DIP.

See also:

http://www.adam-bien.com/roller/abien/entry/service_s_new_serviceimpl

http://martinfowler.com/bliki/InterfaceImplementationPair.html

https://blog.8thlight.com/uncle-bob/2014/05/10/WhenToMock.html

http://wrschneider.github.io/2015/07/27/foo-fooimpl-pairs.html

ContentLicense: CC BY-SA 4.0


问:
Difference between '\n' and '\r\n'
Yes yes, I am aware that '\n' writes a newline in UNIX while for Windows there is the two character sequence: '\r\n'. All this is very nice in theory, but my question is why? Why the carriage return character is extra in Windows? If UNIX can do it in \n why does it take Windows two characters to do this?

I am reading David Beazley's Python book and he says:

For example, on Windows, writing the
  character '\n' actually outputs the
  two- character sequence '\r\n' (and
  when reading the file back, '\r\n' is
  translated back into a single '\n'
  character).

Why the extra effort?

I will be honest. I have known the difference for a long time but have never bothered to ask WHY. I hope that is answered today.

Thanks for your time.

答:
Backward compatibility.

Windows is backward compatible with MS-DOS (aggressively so, even) and MS-DOS used the CR-LF convention because MS-DOS was compatible with CP/M-80 (somewhat by accident) which used the CR-LF convention because that was how you drove a printer (because printers were originally computer controlled typewriters).

Printers have a separate command to move the paper up one line to a new line, and a separate command for returning the carriage (where the paper was mounted) back to the left margin.

That's why.  And, yes, it is an annoyance, but it is part of the package deal that allowed MS-DOS to win over CP/M, and Windows 95 to win over all the other GUI's on top of DOS, and Windows XP to take over from Windows 98.

(Note: Modern laser printers still have these commands because they too are backwards compatible with earlier printers - HP in particular do this well)

For those unfamiliar with typewriters, here is a video showing how typing was done:  http://www.youtube.com/watch?v=LJvGiU_UyEQ.  Notice that the paper is first moved up, and then the carriage is returned, even if it happens in a simple movement.  The ding notified the typist that the end was near, and to prepare for it.

Title: Difference between '\n' and '\r\n'


问:
Inefficient use of interfaces in OOP (C#)
In my code, I've got two interfaces, let's say IOpenable and IExaminable. IOpenable allows the user to Open or Close the object, and IExaminable allows the user to Examine the object.

Now, we have some sort of Tile structure which contains objects which adhere to the following: Not all objects are openable, not all objects are examinable, some are both.

When the user right clicks a Tile in-map, I want to populate some sort of list with the possible targets and their varied functionalities.

As a concrete example, let's say that a Book is examinable and openable, whereas a Card is just examinable. When I right click, I wanted to make it so that I can navigate through Open -> Book or Examine -> [Card | Book].

At the moment, I'm essentially copy/pasting code, where I assess each time if any object is IOpenable and add it to a list of Open targets. Then I do the same for Close, then IExaminable with Examine. I'm tying the functionality of the button to a delegate e.g. [Open -> Book] would have the functionality

```<code>delegate
{
    lockedInteractable.Open();
}
</code>```

The problem with this is, I'm reusing the same code every single time, just changing which interface we're looking for (e.g. changing IOpenable to IExaminable) and changing the function in the delegate (e.g. .Open() to .Examine() or whatever).

Is there a more efficient way to do this? Is this simply a product of my bad code practice in making things implement IOpenable and IExaminable like that?

Clarification

In my setup, Opening results in a shift of sprites, much like closing (I do not want to make this a toggle functionality) and examining actually takes a string in and outputs some flavour text about the object, e.g. "[Bob] examined the [Door], and found it to be very disinteresting."

The duplication of code is essentially as follows:

I start by creating an instance of Button for each examinable. Button then has the on click event linked to .Examine for that examinable object. We then make an instance of Button that opens the menu with all the previously made buttons, and has the text examine. By doing this, we setup a menu with Examine -> Target as described before.

I then create an instance of Button for each openable. Button then has the on-click event linked to .Open for that...

etc for each possible operation and function.

I was hoping to find a way to simply pass in, say, IExaminable or IOpenable and what part I want made into a menu, e.g. .Open and automatically create a menu, rather than repeatedly duplicating the code and just changing the method and interface.

Code

```<code>if(tileInteractable is ILock)
{
        ILock lockedInteractable = tileInteractable as ILock;
        if(lockedInteractable.Locked)
        {
            int lockedItemCount = 0;
            List<string> lockedStrings = new List<string>();
            List<Action> lockedActions = new List<Action>();
            lockedItemCount++;
            lockedStrings.Add (tileInteractable.ObjectName);
            lockedActions.Add(new Action(
                                delegate
                                {
                                lockedInteractable.Unlock (GameManager.instance.player.entity);
                                Reset();
                                }
                            ));
            radComponentCount++;
            buttonStrings.Add ("Unlock");
            actions.Add(new Action(
                                delegate
                                {
                                Reset();
                                GenerateRadial(lockedItemCount,lockedActions,lockedStrings);
                                isActive = true;
                                }
                            ));
        }
}
</code>```

To run you through the code, the following occurs:

A radial menu button is made. It's told to create one button with the entity's name as its hover text.

When pressed, it calls Unlock with the sender as the player, and then closes the radial menu via Reset().

We then create another radial button labelled Unlock that runs the other radial menu when it's pressed. This radial button is then built into a base menu with any other similar ones, so the first menu has Unlock, Examine, etc. if anything exists that implements that functionality, and the second refers to the potential targets.

This code is then nearly identically duplicated, with ILock changed to IExaminable and .Unlock changed to .Examine. Doing this creates the Examine functionality for the main radial menu.

答:
Interfaces are a static tool that allows programmers to guarantee what methods an object supports.

You are trying to use them as a dynamic mechanism for allowing users - or, more precisely, the user interface - to infer the actions users are allowed to do on the the object.

What you need is a uniform way to programmatically access the list of actions at runtime, so that the code creating the UI will be able to iterate over the allowed actions and created buttons for them without caring what each specific action does.

There are two ways to achieve that:

Don't use IOpenable and IExaminable, and instead have each object(or object type) hold a table of allowed actions, that you can register manually.

Use reflection. Basically you want to somehow mark the methods Open, Close and Examine, and have the UI use reflection to get these methods and convert them to buttons for the user. The marking can be done in many ways(depending on what the language supports) - you can depend on the signature, use annotations, use special names, use companion members, place the marking on the interfaces the methods originate from... as long as you can distinguish the user-action methods without specifying each one in the UI generation code.


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

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

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

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

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

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

What is the commonly used pattern to deal with this?

答:
The approach I've used a few times (I'm not sure if it's recommended or not) is as follows:

Code business logic into dedicated business logic classes

Have your entities use these business logic classes so that they aren't anemic

Whether they're injected at construction, or simply directly instantiated is up to you.

Any time I need a certain entity's business logic without an instance of the entity itself I use the corresponding business logic classes.

I've never used this in a large scale application, so I don't know if it has any major limitations.  In other words, YMMV.


问:
How to reference one object with two interfaces?
Suppose I have two interfaces I and J that is implemented by Test class. Now I need one object of class Test that is referenced by I and J both interfaces. I can do it by singleton design pattern. But the problem is sometime I won't need a single object in the program. So there is also another approach that I have known.

```<code>I i = new Test();
i.doSomeThing();
J j = (J) i;
j.print();
</code>```

My question, is there any better way to do this ?
...UPDATE...

```<code>public interface I {
void doSomeThing();
}

public interface J {
void print();
}

public class Test implements I, J{
private int a;

@Override
public void doSomeThing() {
    a += 10;
}

@Override
public void print() {
    System.out.println(this.a);
}
}
</code>```

...UPDATE...

```<code>public class Main {
    public static void main(String[] args) {
    I i = new Test();
    foo(i);
    J j = (J) i;
    ffoo(j);
}
/**
* This method has business with only the doSomething method that
* implement the Test class. This method has not nothing with the print
* method that is in the Test class. So it would be well that only pass
* the I interface to the foo method.
*/
public static void foo(I i) {
    i.doSomeThing();
}

public static void ffoo(J j) {
    j.print();
}
}
</code>```

答:
Why not this?

```<code>public class Main {

    public static void main(String[] args) {
        Test i = new Test();
        foo(i);
        ffoo(i);
    }

    public static void foo(I i) {
        i.doSomeThing();
    }

    public static void ffoo(J j) {
        j.print();
    }
}
</code>```

It looks like, in the context of your code, you need a Test instance.

You don't need to cast your Test to I or J.  Let polymorphism do its magic for you.

Body:
Why not this?

public class Main {

    public static void main(String[] args) {
        Test i = new Test();
        foo(i);
        ffoo(i);
    }

    public static void foo(I i) {
        i.doSomeThing();
    }

    public static void ffoo(J j) {
        j.print();
    }
}

It looks like, in the context of your code, you need a Test instance.

You don't need to cast your Test to I or J.  Let polymorphism do its magic for you.


答:
I would call one object's method from the other, to avoid code replication.

I would find a way to do this like that :

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

    public function banUser($userId)
    {
        $this->userRepo->getUser($userId)->ban()
    }
}
</code>```

or the other way (maybe better, if there is a banService need) :

```<code>class User
{
    public function ban()
    {
        // get your banService instance, which could be a singleton and put it in $ban_service
        $ban_service->banUser($this->userId)
    }
}
</code>```

Title: How to reuse domain model logic in services?

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

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

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

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

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

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

What is the commonly used pattern to deal with this?

Body:
I would call one object's method from the other, to avoid code replication.

I would find a way to do this like that :

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

    public function banUser($userId)
    {
        $this->userRepo->getUser($userId)->ban()
    }
}

or the other way (maybe better, if there is a banService need) :

class User
{
    public function ban()
    {
        // get your banService instance, which could be a singleton and put it in $ban_service
        $ban_service->banUser($this->userId)
    }
}


问:
What is ant build file and maven build file?
Can somebody please tell me in simple words what exactly is ant build file and maven build file?</p>

答:
They're just like any other build files (NAnt, make, ...).

They describe the steps taken to produce some kind of artifact - an executable file, a test run, etc.

The build file will describe how to create a clean build environment, what to compile, where the dependencies are that you need to compile, where to put the executables, DLLs, and the like, any additional programs you need to execute (like running your testrunner on your project, or instrumenting your code so a coverage tool can analyse your test coverage).


答:
I have done it many ways.  The approach you took is effective, though I often find my code is more readable if I use some extra characters on the variable name to help identify that there is one object, and I'm merely connecting to two facets of it:

```<code>I myTestObject_i = new Test(); // creates a test, casts it to I
J myTestObject_j = (J)myTestObject_i;
myTestObject_i.doSomething();
myTestObject_j.print();
</code>```

It's wordy, but I found that in my environment, the words were worth it.

Another approach which we are working with is to use a facade pattern.  In our case, using C++ and many tempates, we are getting a lot of autogeneration.  However, in a pinch, you can write one manually

```<code>class IJFacade : implements I, implements J
{
    public IJFacade(BaseClass obj)
    {
       mObj = obj;
       mI = (I) obj;
       mJ = (J) obj;
       // error checking
    }

    public BaseClass getUnderlyingObject  { return mObj;      }
    public void doSomething()             { mI.doSomething(); }
    public void print()                   { mJ.print();       }

    private BaseClass mObj;
    private I mI;
    private J mJ;
}

Test testObject = new Test();
IJFacade ij = new IJFacade(testObject); // wrap the object to expose functions
ij.doSomething();
ij.print();
</code>```

The best approach really depends on your application, so I encourage experimenting.

Title: How to reference one object with two interfaces?

Body:
Suppose I have two interfaces I and J that is implemented by Test class. Now I need one object of class Test that is referenced by I and J both interfaces. I can do it by singleton design pattern. But the problem is sometime I won't need a single object in the program. So there is also another approach that I have known.

```<code>I i = new Test();
i.doSomeThing();
J j = (J) i;
j.print();
</code>```

My question, is there any better way to do this ?
...UPDATE...

```<code>public interface I {
void doSomeThing();
}

public interface J {
void print();
}

public class Test implements I, J{
private int a;

@Override
public void doSomeThing() {
    a += 10;
}

@Override
public void print() {
    System.out.println(this.a);
}
}
</code>```

...UPDATE...

```<code>public class Main {
    public static void main(String[] args) {
    I i = new Test();
    foo(i);
    J j = (J) i;
    ffoo(j);
}
/**
* This method has business with only the doSomething method that
* implement the Test class. This method has not nothing with the print
* method that is in the Test class. So it would be well that only pass
* the I interface to the foo method.
*/
public static void foo(I i) {
    i.doSomeThing();
}

public static void ffoo(J j) {
    j.print();
}
}
</code>```

Body:
I have done it many ways.  The approach you took is effective, though I often find my code is more readable if I use some extra characters on the variable name to help identify that there is one object, and I'm merely connecting to two facets of it:

I myTestObject_i = new Test(); // creates a test, casts it to I
J myTestObject_j = (J)myTestObject_i;
myTestObject_i.doSomething();
myTestObject_j.print();

It's wordy, but I found that in my environment, the words were worth it.

Another approach which we are working with is to use a facade pattern.  In our case, using C++ and many tempates, we are getting a lot of autogeneration.  However, in a pinch, you can write one manually

class IJFacade : implements I, implements J
{
    public IJFacade(BaseClass obj)
    {
       mObj = obj;
       mI = (I) obj;
       mJ = (J) obj;
       // error checking
    }

    public BaseClass getUnderlyingObject  { return mObj;      }
    public void doSomething()             { mI.doSomething(); }
    public void print()                   { mJ.print();       }

    private BaseClass mObj;
    private I mI;
    private J mJ;
}

Test testObject = new Test();
IJFacade ij = new IJFacade(testObject); // wrap the object to expose functions
ij.doSomething();
ij.print();

The best approach really depends on your application, so I encourage experimenting.


问:
Why does C# have both out and ref?
C# has the out and ref keywords. Why are these two required?
Disclaimer: I don't have deep knowledge of C#.

答: Implementation-wise, they're essentially the same thing, but out communicates something that ref doesn't: you don't care about input.  This means certain things to you and to tooling.  For example, you can pass an uninitialized variable to an out parameter and that's not a problem, where otherwise it would be, and within the function you are required to assign a value to the out parameter before it returns, whereas there's no requirement to do anything at all with a ref value.

Title: Why does C# have both out and ref?


答:
To understand these two keywords, you'll need to understand what passing a value by reference means.  Essentially it means that, if you modify the parameter variable that you pass in within the method or function, that variable retains its modified value when your function exits. Declaring
a parameter as ref or out accomplishes this, whereas an ordinary parameter variable would retain its original value, even if you modified it in the function.

The only differences between ref and out is that out doesn't require you to initialize the variable before you pass it into the function, but ref does; while out does require you to assign something to the variable within the function, but ref doesn't.

Title: Why does C# have both out and ref?

Body:
C# has the out and ref keywords. Why are these two required?
Disclaimer: I don't have deep knowledge of C#.


问:
Most useful features of VIM that aren't standard in a IDE
I'm considering whether I should start using VIM again instead of an IDE. What are the most useful features of VIM that aren't standard in an IDE?</p>

答:
For me the :global command is a killer app.  It will execute arbitrary vim commands on any line that matches (or does not match) a regex.

Here are some examples:

The default behaviour is to list out every line that matches, so:

```<code>:g/TODO:/
</code>```

will list every line that contains the text "TODO:"

change 'Mickey' to 'Minnie' on any line that also contains the word 'Mouse'

```<code>:g/Mouse/ s/Mickey/Minnie/
</code>```

The commands can have their own range, so this will delete from every line with "TODO:" to the next blank line:

:g/TODO:/ .,/^$/ d

Use :g! to execute on every line that does NOT match the regex, e.g. to replace "emacs" with "vim" except on lines that contain the word "sucks":

```<code>:g!/sucks/ s/emacs/vim/
</code>```

Body:
For me the :global command is a killer app.  It will execute arbitrary vim commands on any line that matches (or does not match) a regex.

Here are some examples:

The default behaviour is to list out every line that matches, so:

:g/TODO:/

will list every line that contains the text "TODO:"

change 'Mickey' to 'Minnie' on any line that also contains the word 'Mouse'

:g/Mouse/ s/Mickey/Minnie/

The commands can have their own range, so this will delete from every line with "TODO:" to the next blank line:

:g/TODO:/ .,/^$/ d

Use :g! to execute on every line that does NOT match the regex, e.g. to replace "emacs" with "vim" except on lines that contain the word "sucks":

:g!/sucks/ s/emacs/vim/


问:
Why would I care about the asymptotic growth of the lower bound of the worst case time/space?
In mathematics, there are notations for asymptotic lower bounds, upper bounds, and tight (within-a-constant-factor) bounds. When describing the growth of functions in general, it makes sense that all three might be relevant to some function or other.

In algorithm analysis, asymptotic notation is usually used to describe the growth in time or space requirements.

To me, it seems logical that I may be interested in the maximum, the minimum or the expected requirements. Ignoring the expected requirements, I might be interested in the lower bound of the best case (minimum space/time) or the upper bound of the worst case (maximum space/time).

I can't imagine why I should ever be interested in the lower bound of the worst case or the upper bound of the best case. Since the lower bound is a kind of best case and the upper bound a kind of worst case, these seem like "best case of the worst case" and "worst case of the best case" mismatches to me.

But on several occasions, I've had replies to answers/comments that suggest this may be a failure of imagination on my part.

So - what is it that I'm failing to imagine?

I won't consider a statement along the lines of "it's quite common to say that the lower bound of the worst case of the blah algorithm is blah" to answer the question, unless it also says why people care.

答: I'm not sure what the upper bound of the best case would be good for, but at times it may be useful to identify the lower bound for the worst case for the best possible algorithm that could perform a given task.  Such information could be useful if one has an algorithm that e.g. runs in time O(N^2lgN) and is trying to decide if one should try to find something better.  If one can determine that the lower worst-case bound for an algorithm that can accomplish what needs to be done will be O(N^2lg(lgN)), that would imply that the algorithm one had was close to being within a constant factor of optimal.  If instead lower-bound analysis yielded O(lgN), that would suggest that there might possibly be much more room for improvement.


问:
Migrating a Grails application to Scala Play/Spray
We have a moderately sized Grails web application using GORM/Hibernate over PostgreSQL and GSPs serving HTML, and also a few REST APIs. We are standardising on Scala, and would like to migrate this application to Play or Spray, with Slick to access the existing database.

Nimble is currently used for authentication/authorisation and user/role/etc. management.

What are the approaches we can take in order to do the migration step by step, avoiding a big bang migration?

They are both JVM languages, is there a way to avoid treating them as separate web apps running on separate ports at arms length?

答:
Personally, a rewrite sounds more efficient to me, but if you need to do it in stepwise pieces I would suggest you take the following approach:

Move your existing database code to use Slick (you'll probably need wrappers around it to shield your existing code from too many changes).

Next, integrate Play into your runtime and use Silhouette for authentication and authorization with Play Actions.

You should then be able to move individual GSPs to Play/Twirl one at a time.

Unfortunately, I don't know of a way to make them listen to the same port so you'd have to redirect from Grails to the Play port in order to make it seamless.


问:
Message queue vs database for delayed tasks
I need to build a system that can handle a fairly high amount of delayed tasks (e.g. scheduled emails). For non-delayed tasks I would go for something like RabbitMQ.

But, is it ok to let tasks lingering in the queue for extended amounts of time, like days?

Would it make more sense to store the tasks in a database and then periodically check whether there are tasks which need to be processed?

答: Systems such as RabbitMQ (or in your case maybe look into Kafka) can offer persistence, or guaranteed delivery, as well as configurable TTL on messages. However, they are not designed as a long-term persistent storage solution, and if we're talking about days, I would actually store the job in a DB as you suggest.</p>


答:
At their core both ref and out provide a mechanism for passing the address of a variable to a method so that it can be updated - assigning to the ref or out parameter updates the variable in the caller's context.  Where they differ is in the guarantees: out guarantees that the variable will be updated, ref does not.

From the other side of the call there are similar differences.  An out parameter to our method is not guaranteed to contain anything useful on arrival and must be set to a value at some point, while a ref parameter can be assumed to have a value and we don't need to do anything specific with it.

This difference has impacts on code analysis, generation and optimization which, while not terribly apparent to us most of the time, can have some effects on the way our programs end up operating.  The code generator can defer allocation of the variable until immediately prior to the call, the optimizer might decide it can reorder some operations more effectively based on the contract, etc.

In terms of usage: as a general rule I use out for situations where I don't care about the content of the variable when it arrives as a parameter and ref when I do.

Title: Why does C# have both out and ref?


问:
Restricting object types that can be added to each other using the Composite Pattern
The Situation: I am building a custom PHP application framework. I have implemented a composite pattern so I can build a object tree representing the page to be rendered. Example:

```<code>abstract class \Block\BlockAbstract {
     protected _blocks = array();
     public function __construct($properties);
     public function getBlocks();
     public function addBlock($block);

     ...

     public function render();

}
</code>```

All of my "block" object inherit from this abstract class which is working out great and rendering has been a snap with the help of a little recursion.

The Problem:
I need a way to validate what classes of blocks can be added to other blocks. For example I have 4 distinct block types I have to consider. Keep in mind that ALL blocks inherit from a single block abstract, these are classifications of behavior of the concrete classes, not to be confused with additional abstracts:

Generic - Generics can have any other block type added to it

Final - Can not have any child blocks added to it.

Parent - A parent is a block that can only have a specific type child added to
it, but can be added to any Generic

Child  - Can only be added to a specific parent. This block can also share the properties of a Generic, Parent or Final

To sum the goal up: Given a concrete block class name, generate a list of all concrete block classes that can be added to it.

Solutions Proposed So Far:

Add a property called "blockClassification" to the block abstract that defines it as a Generic, Final, Parent or Child and hard code the logic into a validate function that gets called in the from the addBlock($block) method.

I don't like this solution for a number of reasons, but mainly it still doesn't give me a clear path for defining what the concrete parents and children are that can be allowed. For instance, I have a concrete class \Block\Tabs that is a parent. It can only have \Block\Tabs\Panel blocks added to it, and \Block\Tabs\Panel can only be added to \Block\Tabs. Additional properties would have to be added to build those relationships, and those properties could be examined to derive the "block classification" making this approach impractical.

Add allowedChildTypes property to the block that defines a list of concrete classes that can be added. For ease of use 2 values have specific meaning, a * that represents all block types, and NULL value that means no blocks can be added. For all other cases a coma delimited string of class names is provided and only those classes or classes that inherit from them are allowed

I'm leaning towards this direction because PHP gives me the InstaceOf operator. I can use this to do the checks, when I have new concrete classes that extend the base set, that check will return the same results as its parent class. My only hesitation is that while this method definitely solves the problem of "Given a concrete block class name, generate a list of", I feel like it limits me in the future in that I can only do the search down the tree and not back up. I.e. "Given a child block class name, generate a list of parent blocks it can be added to"

I'm sure that I am not the only one to ever run into the problem, so my question to the masses is: What is the best way to approach/solve this problem?

Additional Information:

If you where wondering how I'm getting a list of all the classes in the first place, the framework implements PSR-0 so I am scanning the directory tree to derive all of the class names, then dynamically instantiating them.

```<code>$allClassNames = scanDirectories(); // Returns array of strings ex: array('\Block\Classname1','\Block\Classname2');
foreach($allClassNames as $className){
  $object = new $className();
}
</code>```

答:
Composite often goes hand in hand with Builder pattern to address exactly the problem you have mentioned here.
You can create a separate class, call it PageBuilder (or whatever suits your fancy) and move all the building logic into that class.
Although I don't know the internals of your code but considering a very generic composite/builder duo here is some sample code for your ref that can get you started.

```<code>class PageEelement()
{
    //properties & methods of basic composite element
    public add(PageEelementInterface $element){

    }
    public remove(PageEelementInterface $element){

    }

    ....
    ....
}

/* Next comes the Builder */

class PageBuilder(){

    $protected $page;

    public construct(PageEelementInterface $page){
        $this->page = $page;
    }
    public addBlock($params){
        //block creation with rules
        if($param == x)
            $block =  new PageElement($paramas);
        } else {
            $block =  new PageElement($paramas);
        }
        $this->page->add($block);

    }

    public function addPanel($params){
        //panel building conditions and validation
    }

    public render(){
        $this->page->render();
    }
}
</code>```

and you can call it like

```<code>$page = new PageElement('title', 'width', 'height');
$pageBuilder = new PageBuilder($page);
$pageBuilder->addBlock('title', 'width', 'height');
$pageBuilder->addPanel(params);

$pageBuilder->render();
</code>```

Body:
Composite often goes hand in hand with Builder pattern to address exactly the problem you have mentioned here.
You can create a separate class, call it PageBuilder (or whatever suits your fancy) and move all the building logic into that class.
Although I don't know the internals of your code but considering a very generic composite/builder duo here is some sample code for your ref that can get you started.

class PageEelement()
{
    //properties & methods of basic composite element
    public add(PageEelementInterface $element){

    }
    public remove(PageEelementInterface $element){

    }

    ....
    ....
}

/* Next comes the Builder */

class PageBuilder(){

    $protected $page;

    public construct(PageEelementInterface $page){
        $this->page = $page;
    }
    public addBlock($params){
        //block creation with rules
        if($param == x)
            $block =  new PageElement($paramas);
        } else {
            $block =  new PageElement($paramas);
        }
        $this->page->add($block);

    }

    public function addPanel($params){
        //panel building conditions and validation
    }

    public render(){
        $this->page->render();
    }
}

and you can call it like

$page = new PageElement('title', 'width', 'height');
$pageBuilder = new PageBuilder($page);
$pageBuilder->addBlock('title', 'width', 'height');
$pageBuilder->addPanel(params);

$pageBuilder->render();


问:
What uses does Smalltalk’s ‘become:’ have?
The become: message in Smalltalk causes one object to change into another, affecting all references to it.

What uses does this language feature have? Does it get used in real code? Is it just a curiosity? Is it considered a good/bad practice to use it?

答:
Gilad Bracha talks about become: at some length:

One of Smalltalk’s most unique and powerful features is also one of
  the least known outside the Smalltalk community. It’s a little method
  called become: .

What become: does is swap the identities of its receiver and its
  argument. That is, after

a become: b

all references to the object denoted by a before the call point refer
  to the object that was denoted by b, and vice versa.

Take a minute to internalize this; you might misunderstand it as
  something trivial. This is not about swapping two variables - it is
  literally about one object becoming another. I am not aware of any
  other language that has this feature. It is a feature of enormous
  power - and danger.

Consider the task of extending your language to support persistent
  objects. Say you want to load an object from disk, but don’t want to
  load all the objects it refers to transitively (otherwise, it’s just
  plain object deserialization). So you load the object itself, but
  instead of loading its direct references, you replace them with husk
  objects.

The husks stand in for the real data on secondary storage. That data
  is loaded lazily. When you actually need to invoke a method on a husk,
  its doesNotUnderstand: method loads the corresponding data object from
  disk (but again, not transitively).

Then, it does a become:, replacing all references to the husk with
  references to the newly loaded object, and retries the call.

Some persistence engines have done this sort of thing for decades -
  but they usually relied on low level access to the representation.
  Become: lets you do this at the source code level.

Now go do this in Java. Or even in another dynamic language. You will
  recognize that you can do a general form of futures this way, and
  hence laziness. All without privileged access to the workings of the
  implementation. It’s also useful for schema evolution - when you add
  an instance variable to a class, for example. You can “reshape” all
  the instances as needed.

Of course, you shouldn’t use become: casually. It comes at a cost,
  which may be prohibitive in many implementations. In early Smalltalks,
  become: was cheap, because all objects were referenced indirectly by
  means of an object table. In the absence of an object table, become:
  traverses the heap in a manner similar to a garbage collector. The
  more memory you have, the more expensive become: becomes.

Having an object table takes up storage and slows down access; but it
  does buy you a great deal of flexibility. Hardware support could ease
  the performance penalty. The advantage is that many hard problems
  become quite tractable if you are willing to pay the cost of
  indirection via an object table up front. Remember: every problem in
  computer science can be solved with extra levels of indirection. Alex
  Warth has some very interesting work that fits in this category, for
  example.

Become: has several variations - one way become: changes the identity
  of an object A to that of another object B, so that references to A
  now point at B; references to B remain unchanged. It is often useful
  to do become: in bulk - transmuting the identities of all objects in
  an array (either unidirectionally or bidirectionally). A group become:
  which does it magic atomically is great for implementing reflective
  updates to a system, for example. You can change a whole set of
  classes and their instances in one go.

You can even conceive of type safe become: . Two way become: is only
  type safe if the type of A is identical to that of B, but one way
  become: only requires that the new object be a subtype of the old one.

It may be time to reconsider whether having an object table is
  actually a good thing.

Effectively what you get is a form of lazy loading via what amounts to metaprogramming. As Bracha points out this can be very useful but it's also dangerous since it can carry a serious performance impact.


问:
Are SMART goals useful for programmers?
Several organisations I know use SMART goals for their programmers. SMART is an acronym for Specific, Measurable, Achievable, Relevant and Time-Bound. They are fairly common in large corporations.

My own prior experience with SMART goals has not been all that positive. Have other programmers found them an effective way to measure performance? What are some examples of good SMART goals for programmers (if they exist).

答:
SMART is an acronym to remember some criteria for better goals. So introducing SMART means, your management has to make better following this principle. Without SMART management would set goals anyways, but they would be more likely too difficult.

So, for programmers should come no change, the management has to change it's style to implement SMART. And if they do right, your work as a programmer can become easier, because the direction of the project is more clear, timeframes are set and so on.

If management doesn't do it right, not much will change.

Title: Are SMART goals useful for programmers?


问:
Is it valid to expect/throw an exception using a custom caching system?
Imagine some code like the following:

```<code>class Cache {
    private Map<String, String> values = new HashMap<String, String>();

    public String getFromCache(String key) {
        if (!values.containsKey(key)) {
            throw new NoEntryException();
        }
        return values.get(key);
    }

    public void setInCache(String key, String value) {
        this.values.put(key, value);
    }
}

class Foo {

    private Cache cache = new Cache();

    public String bla(String foo) {
        try {
            return cache.getFromCache(foo);
        } catch (NoEntryException ex) {
            String result = doSomeHeavyOperation(foo);
            cache.setInCache(foo, result);
        }
    }

    public String doSomeHeavyOperation(String something) {
        // heavy operation
        return something;
    }
}
</code>```

Is this a valid use case for an exception? On one hand, it might be computationally slower to throw the exception, than doing a "cacheContains(String)" method or checking for null (although in that case, does null mean "contains no element" or "always null for doSomeHeavyOperation"?). On the other hand it does affect the control flow, but it doesn't seem to do so in a way that makes it less clear to me. I'd even say it looks cleaner to me than checking up front using a cacheContains(String).

The values in the cache are always the same, for the sake of simplicity (although you can expect a cache invalidation after 30 minutes).

Of course the cache used here is quite simple, but later on will be a wrapper around a more complicated system, like a redis integration.

Edit:

Here is some example code on how to do the accepted answer in Java (needs improvement with generics, multiple arguments, etc):

```<code>abstract class MissingResultCaller {
abstract String doCall(String argument);
}

class Cache {
private Map<String, String> values = new HashMap<String, String>();

public String getFromCache(String key, MissingResultCaller missingResultCaller) {
    if (!values.containsKey(key)) {
        String value = missingResultCaller.doCall(key);
        setInCache(key, value);
        return value;
    }
    return values.get(key);
}

public void setInCache(String key, String value) {
    this.values.put(key, value);
}
}

class Foo {

private Cache cache = new Cache();

public String bla(String foo) {
    return cache.getFromCache(foo, new MissingResultCaller() {
        @Override
        String doCall(String argument) {
            return doSomeHeavyOperation(argument);
        }
    });
}

public String doSomeHeavyOperation(String something) {
    System.out.println("Did heavy operation");
    return "heavy operation return";
}
}
</code>```

答:
Generally speaking an exception is called an exception because it should be an exception.

Throwing an exception will (as far as I know, correct me if I'm wrong) invalidate the whole command-pipeline and are therefore to be considered to be very slow. Exceptions will however give you the benefit of not having to perform any null-checks AND allow you to separate error-handling from actual code.

Now to come back to your specific problem: Since your cache is valid for 30 Minutes, performance really isn't an issue. The question you should be asking yourself therefore is:

Is the code readable? - Looks good to me.


答:
You should prefer programmatic checks to exceptions whenever you can. An exception is exceptional, you should only throw them where a condition arises that you cannot correct. And please, don't use them for control flow.

It's fine to throw an exception in your cache GET, but ONLY if you also provide calling code with a way to check beforehand if the exception should be thrown. Have a look at most implementations of a filereader. It will throw an exception if you ask it to read beyond the end of a file, but it will also give you a means of determining if you have reached the end of said file.

Programmatic checks are clearer, easier to read and don't kill your performance. I cringe at the idea that you design a caching layer (intended to improve performance) but at the same time use exceptions in that layer for normal control flow.

If you don't want to return NULL, consider returning an intermediate object. You could return a CacheResult-object from your cache-calls which has a 'CacheStatus' and 'Result'-property. CacheStatus would have a value of either 'Hit' or 'Miss', and in the case of a 'Hit' you could find the cache object in the Result-property. This way you can work around the need for a 'null'-check if that bothers you.

Alternatively, you could pass a function to the cache method to allow the object to be created if it does not exist. Not sure if this can be done in all languages, C# would look a bit like this

```<code>private ResultType GetFromCacheOrCreate<ResultType>(string key, Func<ResultType> createFunction)
{
    var result = _myCache.Get<ResultType>(key);
    if(result == null)
        return createFunction();
    else
        return result;
}

private string doSomeHeavyOperation()
{
    //do something here
}

var myValue = GetFromCacheOrCreate<string>("mycachedValue", () => { return doSomeHeavyOperation(); });
</code>```

Title: Is it valid to expect/throw an exception using a custom caching system?

Body:
Imagine some code like the following:

```<code>class Cache {
    private Map<String, String> values = new HashMap<String, String>();

    public String getFromCache(String key) {
        if (!values.containsKey(key)) {
            throw new NoEntryException();
        }
        return values.get(key);
    }

    public void setInCache(String key, String value) {
        this.values.put(key, value);
    }
}

class Foo {

    private Cache cache = new Cache();

    public String bla(String foo) {
        try {
            return cache.getFromCache(foo);
        } catch (NoEntryException ex) {
            String result = doSomeHeavyOperation(foo);
            cache.setInCache(foo, result);
        }
    }

    public String doSomeHeavyOperation(String something) {
        // heavy operation
        return something;
    }
}
</code>```

Is this a valid use case for an exception? On one hand, it might be computationally slower to throw the exception, than doing a "cacheContains(String)" method or checking for null (although in that case, does null mean "contains no element" or "always null for doSomeHeavyOperation"?). On the other hand it does affect the control flow, but it doesn't seem to do so in a way that makes it less clear to me. I'd even say it looks cleaner to me than checking up front using a cacheContains(String).

The values in the cache are always the same, for the sake of simplicity (although you can expect a cache invalidation after 30 minutes).

Of course the cache used here is quite simple, but later on will be a wrapper around a more complicated system, like a redis integration.

Edit:

Here is some example code on how to do the accepted answer in Java (needs improvement with generics, multiple arguments, etc):

```<code>abstract class MissingResultCaller {
abstract String doCall(String argument);
}

class Cache {
private Map<String, String> values = new HashMap<String, String>();

public String getFromCache(String key, MissingResultCaller missingResultCaller) {
    if (!values.containsKey(key)) {
        String value = missingResultCaller.doCall(key);
        setInCache(key, value);
        return value;
    }
    return values.get(key);
}

public void setInCache(String key, String value) {
    this.values.put(key, value);
}
}

class Foo {

private Cache cache = new Cache();

public String bla(String foo) {
    return cache.getFromCache(foo, new MissingResultCaller() {
        @Override
        String doCall(String argument) {
            return doSomeHeavyOperation(argument);
        }
    });
}

public String doSomeHeavyOperation(String something) {
    System.out.println("Did heavy operation");
    return "heavy operation return";
}
}
</code>```

Body:
You should prefer programmatic checks to exceptions whenever you can. An exception is exceptional, you should only throw them where a condition arises that you cannot correct. And please, don't use them for control flow.

It's fine to throw an exception in your cache GET, but ONLY if you also provide calling code with a way to check beforehand if the exception should be thrown. Have a look at most implementations of a filereader. It will throw an exception if you ask it to read beyond the end of a file, but it will also give you a means of determining if you have reached the end of said file.

Programmatic checks are clearer, easier to read and don't kill your performance. I cringe at the idea that you design a caching layer (intended to improve performance) but at the same time use exceptions in that layer for normal control flow.

If you don't want to return NULL, consider returning an intermediate object. You could return a CacheResult-object from your cache-calls which has a 'CacheStatus' and 'Result'-property. CacheStatus would have a value of either 'Hit' or 'Miss', and in the case of a 'Hit' you could find the cache object in the Result-property. This way you can work around the need for a 'null'-check if that bothers you.

Alternatively, you could pass a function to the cache method to allow the object to be created if it does not exist. Not sure if this can be done in all languages, C# would look a bit like this

private ResultType GetFromCacheOrCreate<ResultType>(string key, Func<ResultType> createFunction)
{
    var result = _myCache.Get<ResultType>(key);
    if(result == null)
        return createFunction();
    else
        return result;
}

private string doSomeHeavyOperation()
{
    //do something here
}

var myValue = GetFromCacheOrCreate<string>("mycachedValue", () => { return doSomeHeavyOperation(); });


问:
What is the most accepted transaction strategy for microservices
One of the major issues that I have seen occur in a system with microservices is the way transactions work when they span over different services. Within our own architecture, we have been using distributed transactions to resolve this, but they come with their own issues. Especially deadlocks have been a pain so far.

Another option seems to be some kind of custom-made transaction manager, which knows the flows within your system, and will take care of the rollbacks for you as a background process spanning over your entire system (so it will tell the other services to rollback and if they're down, notify them later on).

Is there another, accepted option? Both of these seem to have their disadvantages. The first one could cause deadlocks  and a bunch of other issues, the second one could result in data inconsistency. Are there better options?

答:
I think the standard wisdom is to never have transactions cross microservice boundaries. If any given set of data really needs to be atomically consistent with another, those two things belong together.

This is one of the reasons it is very hard to split a system into services until you have fully designed it. Which in the modern world probably means written it...


问:
Which JavaScript Template (jst) syntax uses double-brackets, (e.g. [[ and ]] )?
I'm looking at the source code for a Rails application that uses Backbone and there are template files with .jst.ejs extensions.

The templates include HTML with lines of JavaScript wrapped in double-square-brackets like this this example:

```<code>[[ if (currentUser) { ]]
  <h1>Welcome, back!</h1>
[[ } else { ]]
  <h1>Please sign up!</h1>
[[ } ]]
</code>```

What is the name of this template syntax?

答:
I'm not sure if many template syntaxes have a specific name. A lot of template syntaxes are unique, but there are frameworks out there that use similar templating syntaxes without actually calling them anything. Mostly, they are referred to by the name of the engine.

For example, both Twig (a templating engine that can be used with the Symfony Framework for PHP) and AngularJS (a javascript Framework) have ways of binding by means of the {{ }} syntax. A code sample could be said to be using a Twig-like or Angular-like syntax, but as far as I know there are very few templating syntaxes out there that are standardized and implemented in different engines and can therefore be 'named'.


问:
Class with members that are mutable during creation but immutable afterwards
I have an algorithm which creates a collection of objects.  These objects are mutable during creation, since they start out with very little, but then they are populated with data in different places within the algorithm.

After the algorithm is completed, the objects should never be changed - however they are consumed by other parts of the software.

In these scenarios, is it considered good practice to have two versions of the class, as described below?

The mutable one is created by the algorithm, then

On completion of the algorithm, the data is copied into immutable objects which are returned.

答: You can perhaps use the builder pattern. It uses a separate 'builder' object with the purpose of collecting the necessary data, and when all data is collected it creates the actual object. The created object can be immutable.</p>


答:
You can use the Builder pattern as @JacquesB says, or alternatively think why is it actually that these objects of yours have to be mutable during creation?

In others words, why does the process of creating them have to be spread in time, as opposed to passing all the required values into the constructor and creating instances in one go?

Because the Builder could be a good solution for the wrong problem.

If the issue is that you end up with a constructor that's like 10 parameters long, and you'd like to mitigate it by building the object little by little, it could indicate that the design is messed up, and these 10 values should be "bagged" / grouped into a few objects... or the main object split into a few smaller ones...

In which case - stick to immutability all the way, just improve the design.

Title: Class with members that are mutable during creation but immutable afterwards

Body:
I have an algorithm which creates a collection of objects.  These objects are mutable during creation, since they start out with very little, but then they are populated with data in different places within the algorithm.

After the algorithm is completed, the objects should never be changed - however they are consumed by other parts of the software.

In these scenarios, is it considered good practice to have two versions of the class, as described below?

The mutable one is created by the algorithm, then

On completion of the algorithm, the data is copied into immutable objects which are returned.


答:
A simple way to achieve this would be to have an interface that allows one to read properties and call only read only methods and a class that implements that interface which also lets you write that class.

Your method that creates it, deals with the former, and then returns the latter providing only a read only interface to interact with.  This would require no copying and it allows you to easily fine-tune behaviors you want available to the caller as opposed to the creator.

Take this example:

```<code>public interface IPerson
{
    public String FirstName
    {
        get;
    }

    public String LastName
    {
        get;
    }
}

public class PersonImpl : IPerson
{
    private String firstName, lastName;

    public String FirstName
    {
        get { return firstName; }
        set { firstName = value; }
    }

    public String LastName
    {
        get { return lastName; }
        set { lastName = value; }
    }
}

class Factory
{
    public IPerson MakePerson()
    {
        PersonImpl person = new PersonImpl();
        person.FirstName = 'Joe';
        person.LastName = 'Schmoe';
        return person;
    }
}
</code>```

The only disadvantage to this approach is that one could simply cast it to the implementing class.  If it were a matter of security, then simply using this approach is insufficient.  A workaround for this is that you can create a facade class to wrap the mutable class, which simply presents an interface that the caller works with and cannot have access to the internal object.

In this way, not even casting will help you.  Both can derive from the same read only interface, but casting the returned object will only give you the Facade class, which is immutable as it doesn't change the underlying state of the wrapped mutable class.

It's worth mentioning that this doesn't follow the typical trend in which an immutable object is constructed once and for all through its constructor.  Understandably, you might be having to deal with many parameters, but you should ask yourself if all these parameters need to be defined up front or if some can be introduced later.  In that case, a simple constructor with only required parameters should be used.  In other words, don't use this pattern if it is covering up another problem in your program.

Body:
A simple way to achieve this would be to have an interface that allows one to read properties and call only read only methods and a class that implements that interface which also lets you write that class.

Your method that creates it, deals with the former, and then returns the latter providing only a read only interface to interact with.  This would require no copying and it allows you to easily fine-tune behaviors you want available to the caller as opposed to the creator.

Take this example:

public interface IPerson
{
    public String FirstName
    {
        get;
    }

    public String LastName
    {
        get;
    }
}

public class PersonImpl : IPerson
{
    private String firstName, lastName;

    public String FirstName
    {
        get { return firstName; }
        set { firstName = value; }
    }

    public String LastName
    {
        get { return lastName; }
        set { lastName = value; }
    }
}

class Factory
{
    public IPerson MakePerson()
    {
        PersonImpl person = new PersonImpl();
        person.FirstName = 'Joe';
        person.LastName = 'Schmoe';
        return person;
    }
}

The only disadvantage to this approach is that one could simply cast it to the implementing class.  If it were a matter of security, then simply using this approach is insufficient.  A workaround for this is that you can create a facade class to wrap the mutable class, which simply presents an interface that the caller works with and cannot have access to the internal object.

In this way, not even casting will help you.  Both can derive from the same read only interface, but casting the returned object will only give you the Facade class, which is immutable as it doesn't change the underlying state of the wrapped mutable class.

It's worth mentioning that this doesn't follow the typical trend in which an immutable object is constructed once and for all through its constructor.  Understandably, you might be having to deal with many parameters, but you should ask yourself if all these parameters need to be defined up front or if some can be introduced later.  In that case, a simple constructor with only required parameters should be used.  In other words, don't use this pattern if it is covering up another problem in your program.


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

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

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

答:
If two services are sufficiently intertwined that it would be a pain to implement them without sharing DTOs and other model objects, that's a strong sign you shouldn't have two services.

Certainly the example makes little sense as two services; it's hard to imagine a specification for 'User management' so complicated it would keep a whole team so busy they don't have time to do authentication.

If for some reason they were, then they would communicate using what are basically arbitrary strings, as in OAuth 2.0.


问:
API with limits vs site crawling
I started working on a website,for tracking and rating watched anime/manga/etc. and recommendations, and it should also have an API, for providing the info about series and other things.

On similar sites, I have noticed that, to use an API, one typically needs a token/auth of sorts, and there are certain usage limits, even if it's for reading info publicly available on the site.

But the problem is, you could circumvent all those limits by crawling the site directly.
Even if the format is less convenient, once you have a parser in place there's no problem. Actually, if it uses clientside rendering, the info will already be sent in a convenient format.
And on the other hand, this would also put more strain on the server, because the info may be spread out on multiple pages, needing more requests, and it would also send info not required by the client app.

In the end, is there a point in restricting the API used for info that's available publicly on the site? Should there be an unrestricted, unauthed API for reading public info, in order to avoid needless blunder for both sides?
Or should, instead, the site itself have request limits, like an API?

答:
Having a public API for data access from your site is about making the data available in a convenient, supported, well-defined and always-up-to-date manner.  It is a way for a site owner to say 'here is data I collect and own, but I want you to be able to use it so I'm making it available. Oh, and I promise not to change the structure or do anything that might break your applications without communicating about it clearly'.

Crawling has some technical limitations, some very important legal considerations AND is prone to breaking without any sort of notification from the owner of the data. Personally I would not hesitate to consume a public JSON API if that has data I need, but I'd be hard pressed to start writing a crawler/parser to get it off a website...

Title: API with limits vs site crawling


问:
Is it necessary to discuss database changes
I am working on a project with a team of 4-5 people. Is it necessary to discuss the database changes with the team before implementing?  I am working on the database api's.

Is it better to discuss this or not? In my team are senior people. So can't I make changes myself and implement the change and explain the changes.

答:
This seems as a design change. This must be done in the design phase. This should get reviewed in the design review.<br>
So my short answer is Yes. Get it reviewed as early as possible. Because if it is not reviewed and someone else has created yet, that person is surely going to get pissed. </p>

Body:
This seems as a design change. This must be done in the design phase. This should get reviewed in the design review.

So my short answer is Yes. Get it reviewed as early as possible. Because if it is not reviewed and someone else has created yet, that person is surely going to get pissed.


答:
I think that if consistency is a strong requirement in your application you should ask yourself if microservices is the better approach. Like Martin Fowler says:

Microservices introduce eventual consistency issues because of their laudable insistence on decentralized data management. With a monolith, you can update a bunch of things together in a single transaction. Microservices require multiple resources to update, and distributed transactions are frowned upon (for good reason). So now, developers need to be aware of consistency issues, and figure out how to detect when things are out of sync before doing anything the code will regret.

But maybe in your case, you can sacrifice Consistency in pos of Availability

Business processes are often more tolerant of inconsistencies than you think because businesses often prize availability more.

However I also ask myself if there exists a strategy for distributed transactions in microservices, but maybe the cost is too high.
I wanted to give you my two cents with the always excellent article of Martin Fowler and the CAP theorem.

Title: What is the most accepted transaction strategy for microservices

Body:
One of the major issues that I have seen occur in a system with microservices is the way transactions work when they span over different services. Within our own architecture, we have been using distributed transactions to resolve this, but they come with their own issues. Especially deadlocks have been a pain so far.

Another option seems to be some kind of custom-made transaction manager, which knows the flows within your system, and will take care of the rollbacks for you as a background process spanning over your entire system (so it will tell the other services to rollback and if they're down, notify them later on).

Is there another, accepted option? Both of these seem to have their disadvantages. The first one could cause deadlocks  and a bunch of other issues, the second one could result in data inconsistency. Are there better options?


问:
Integration testing and database connection string in app.config
I am working on a project where SqlConnection is created via a static method, lets say it's DatabaseAccess.GetSqlConnection(). This method reads the .config file to get the connection string and creates a connection.

Is it ok to refactor the code to use an ISqlConnectionCreator (or ISqlConnectionFactory) responsible for creating the actual connections just for the sake of testing (as it seems more "by the book" for me) or go easy and just create a .config file in the test project containing test connection strings?

The second solution seems more error-prone and creates an indirect relation between tests and the tested classes.

I want to make sure there is a justification for the extra work of refactoring code to use the injected connection creator.

答:
I'm having a hard time seeing the benefit from this extra code. Code is a liability and unless there is an actual problem I probably wouldn't want to spend time on it.

I would just create the app.config file and call it a day.


答:
Token-authorized APIs are used for lots of reasons.

Controlling access to restricted information.  Since a token usually maps somehow to an authorized identity, the site can restrict programmatic access to data exactly as it would to interactive access via the web UI.  Tokens also prevent passwords from being disclosed in requests, and are usually revocable by both the user and the site.

Rate-limiting individual consumers.  Since programs can easily present load many times higher and faster than people, being able to prevent overloading by an overly-aggressive consumer can make the difference between a site being up or down.

Controlling errant consumers. Some sites issue tokens to the program accessing the site, in addition to, or instead of, the user.  This allows the site to make decisions such as blocking programs that abuse the API, that produce too many invalid requests, etc.

Improving usage statistics.  Interactive usage is usually discussed both in terms of page views and sessions.  API requests are the equivalent of page views, but there is nothing like an API session (unless the site allows persistent idle HTTP sessions, but that's uncommon).  Tokens allow the site to group requests for the same user, and with some time-boxing, that can be a reasonable proxy for a session.

Title: API with limits vs site crawling

Body:
I started working on a website,for tracking and rating watched anime/manga/etc. and recommendations, and it should also have an API, for providing the info about series and other things.

On similar sites, I have noticed that, to use an API, one typically needs a token/auth of sorts, and there are certain usage limits, even if it's for reading info publicly available on the site.

But the problem is, you could circumvent all those limits by crawling the site directly.
Even if the format is less convenient, once you have a parser in place there's no problem. Actually, if it uses clientside rendering, the info will already be sent in a convenient format.
And on the other hand, this would also put more strain on the server, because the info may be spread out on multiple pages, needing more requests, and it would also send info not required by the client app.

In the end, is there a point in restricting the API used for info that's available publicly on the site? Should there be an unrestricted, unauthed API for reading public info, in order to avoid needless blunder for both sides?
Or should, instead, the site itself have request limits, like an API?


答:
Depends what you mean by "discuss".

If by "discuss" you mean "debate" or "design by committee", I say no. The developer who is the owner of a section of an application gets to say what the schema looks like.

If, instead of "discussing" database changes, you change the database and not let anybody know until their code fails, I say yes, "discussion" is critical.

Title: Is it necessary to discuss database changes

Body:
I am working on a project with a team of 4-5 people. Is it necessary to discuss the database changes with the team before implementing?  I am working on the database api's.

Is it better to discuss this or not? In my team are senior people. So can't I make changes myself and implement the change and explain the changes.


问:
What techniques should I use when implementing infinite scrolling on a website?
I am currently working on a website which implements infinite scrolling on it's search page (the results themselves coming from Elastic search) and, unsurprisingly, the more you scroll the slower things get.

This is especially prominent on mobile devices, and in particular lower cost devices (which most people use).

We have put a lot of work into making the site responsive on mobile devices from an HTML/CSS perspective, but inevitably as you add more items to the DOM, things slow down.

I see that sites like Twitter and Facebook do a good job at avoiding this problem, but how? I am guessing it is some form of DOM garbage collection, and items are loaded not just as you scroll down, but up also, and items not in view are GC'd?

Adding to the complexity, we are using the headroom.js library to have the menu needed to alter the search options always available by just scrolling up slightly, and we notice that this action gets slower and more jarred as you scroll down and have more search results to scroll through.

Each search result consists of not just text, but an image also.

Also, the search results are refreshed without a reload of the page, we use two way binding provided by AngularJS for this purpose (pushing search results into, and popping them out of an array which ng-repeat uses to populate the view), but I suspect that users of other libraries (such as Ember.js) face the same problem.

Can somebody elaborate on how we should be approaching this? We have the infinite scrolling aspect (loading more items into the DOM as you scroll) nailed, but on lower end smart phones, things slow down quickly so I am guessing there another aspect to this problem which we have missed.

I assume the trick is to only load items into the DOM that the user can see while keeping the scrollbar as is, and responding to scroll events to load the items the user was expecting to see, but how would we go about this? Are there any libraries available for this purpose?

Thanks

答:
See this: ClusterizeJS

This plugin makes it possible to scroll a huge number of items while keeping DOM lean and small. It removes out of the view items and replaces them with dummy elements that are dynamically resized so scroll positioning is retained as expected.

Facebook doesn't do it this way though, but I suppose this is the best way to have good performance on slow devices.

An additional note on Angular

You should also be aware that pure HTML+CSS pages are much simpler to handle than DHTML that run additional javascript. Angular is particularly hungry in this regard as it has to dirty check model and view to keep them in sync and execute any code related to changes. When your DOM contains a lot of bindings (they say the number is somewhere about 2000) your page suffers. Try using one time bindings implemented in Angular to speed things up especially if your views only display data without users changing the model.


答:
The usual approach is to isolate those microservices as much as possible - treat them as single units. Then transactions can be developed in context of the service as a whole (ie not part of usual DB transactions, though you can still have DB transactions internal to the service).

Think how transactions occur and what kind make sense for your services then, you can implement a rollback mechanism that un-does the original operation, or a 2-phase commit system that reserves the original operation until told to commit for real. Of course both these systems mean you're implementing your own, but then you're already implementing your microservices.

Financial services do this kind of thing all the time - if I want to move money from my bank to your bank, there is no single transaction like you'd have in a DB. You don't know what systems either bank is running, so must effectively treat each like your microservices. In this case, my bank would move my money from my account to a holding account and then tell your bank they have some money, if that send fails, my bank will refund my account with the money they tried to send.