问:
Activity diagram, can merge node have more than 1 output?
There is a simple system, that allows users to do 4 things: ADD, EDIT, DELETE, PRINT data.

I am due to model it (I'm entirely new to UML activity diagrams) and from notation, I dont understand whether a decision node can have more than 3 inputs? It should be, otherwise how would I do that.

Anyway, the user can perform the action and do it again, so there is a loop needed. But the merge node is said to have only one output, which would not be the case.
The picture should be clear what I mean.

答: I am in no way an expert on UML but during my work I often work with UML-alike diagrams and generally I find it works best not to strictly adhere to UML limitations but simply try visualize "what you mean". Unless of course these are your requirements. Is the below what you mean? (generated by code2flow)


问:
Algorithm to create an TicTacToe game AI
What are the algorithms I could use to create an AI for the game TicTacToe.
I have already used Alpha–beta pruning and Predictive modelling. What the other good Algorithms I can use to create this AI.

I want to practice a new language this would a great way to learn a new language.

Thanks

答:
Since Tic-Tac-Toe is a solved game, I would recommend simply playing a perfect game every time.

The following algorithm will allow you (or the AI) to always deny your opponent victory:

Win:

If you have two in a row, you can place a third to get three in a row.

Block:

If the opponent has two in a row, you must play the third to block the opponent.

Fork:

Create an opportunity where you have two threats to win (two non-blocked lines of 2).

Blocking an opponent's fork:

If there is a configuration where the opponent can fork, you must block that fork.

Center:

You play the center if open.

Opposite corner:

If the opponent is in the corner, you play the opposite corner.

Empty corner:

You play in a corner square.

Empty side:

You play in a middle square on any of the 4 sides.

Pick the highest possible on the list

The perfect heuristic is pretty simple in terms of AI programming. The most difficult heuristic part to implement is searching for fork configurations. Once you have that the other checks are next to trivial!

ContentLicense: CC BY-SA 3.0


问:
Should Uncle Bob's example be refactored to an AbstractFactory or a SimpleFactory?
In the book "Clean Code" Robert Martin makes a statement regarding the following code:

```<code>public Money calculatePay(Employee e) throws InvalidEmployeeType {   switch (e.type) {
    case COMMISSIONED:
      return calculateCommissionedPay(e);
    case HOURLY:
      return calculateHourlyPay(e);
    case SALARIED:
      return calculateSalariedPay(e);
    default:
      throw new InvalidEmployeeType(e.type);   } }
</code>```

Statement: The solution to this problem (see Listing 3-5) is to bury the switch statement in the basement of an ABSTRACT FACTORY,9 and never let anyone see it.

What I don't understand is why does he call it an Abstract Factory? If the solution is to create 3 Employee subclasses each implementing it's own CalculatePay method then the logic is moved up to let's say the controller. But then we have to create a "Simple Factory (Idiom)" not an Abstract Factory as presented in the original book from the GOF.

The Abstract Factory has the intent to: "Provide an interface for creating families of related or dependent objects without specifying their concrete classes." but this is clearly not the case.

答:
In that specific example, he could have used a Simple Factory to get the point about the switch statement across.

But one of his other points is that you should be looking for ways to minimize dependencies.  If you have client code that uses the factory to create employee objects and that code refers to a concrete (i.e. simple) factory class, that would be a much tighter coupling than if you refer to an EmployeeFactory interface.  This way if for whatever reason, later down the road you decide current implementation of EmployeeFactoryImpl isn't good enough for you, you will be able to simply define a new factory class implementation that implements the same EmployeeFactory interface.

Because you are already using abstract factory, all the code that stores and passes around EmployeeFactory interface will not need to be touched, which is going back to OCP principle, write code as much as possible so that it is closed to constant modifications, because every time you modify something, there's a risk that you will break it.

So the only thing that Uncle Bob didn't illustrate in that example is that you could have created "class EmployeeFactoryImpl2 implements EmployeeFactory" with a completely different implementation of the body of makeEmployee() method and that would complete GoF's example, but it would add more moving parts to the example that is intended to illustrate something completely different.

The other take away from Clean Code (which IMO is an awesome book, so keep reading it), is that patterns is something to keep in the back of your mind, not something to introduce left and right just because you read GoF. So more importantly what Uncle Bob is illustrating, and that's a perfect example, is that you can make small, incremental refactorings to the code to make it easier to read and maintain and while you are doing it, keep the patterns in the back of your mind because there's no sense of reinventing what's already been done.

In this case he went straight to abstract factory because the difference was typing "public class EmployeeFactory" (simple) vs. "public class EmployeeFactoryImpl implements EmployeeFactory" (abstract).  Abstract factory gives you much better position for the future and YANGI isn't a good argument here because this better positioning only cost you a handful of keystrokes without any extra complexity.


问:
Program design with multiple data sets, algorithms and results
I have a question regarding the design of my software.

There are four different data sets and three consecutive algorithms operating on the data sets and on the results from the previous algorithm runs.

Let D1 - D4 be the set of data sets, A1 - A3 the set of algorithms and R1 - R3 the set of results from the respective algorithms.

A1 uses data sets D1, D2 and D3 and has to run on n different parameters.
A2 uses data sets D1 and D3 as well as R1_1 - R1_n.
A3 uses data sets D1, D2 and D4 as well as R2.

```<code>  D1    D1    D1
  D2    D3    D2
  D3          D4

  |     |     |
  v     v     v

n*A1    A2    A3
     _     _
  |  /| |  /| |
  v /   v /   v

R1_1    R2    R3
...
R1_n
</code>```

Each of the results R1_1 - R1_n, R2 and R3 should have some output functionality.

So my question is how to organize the program and its classes. I guess I would want to create separate classes for each of D1 - D4, A1 - A3 and R1 - R3 and make the data and result objects attributes of the algorithm objects? Are there any reasons for or against creating n objects R1_1 - R1_n instead of one object R1 containing an array of n results?

Should the data classes include their own respective 'readFromFile' functions or would it be better to have a global utility class that reads all data from file and generates the data objects? The same goes for output functions, should they be placed in each of the result classes or should they be globally organized?

Kind regards!

答:
The answer depend on details which is not mentioned in the question.

It will depend on the exact details of D1, D2, ..., A1, A2. Such detail may not be worthwhile to mention in your question, because it will make the question too localized, and few will read all of the details. It may still help to get a more tailored answer.

If you find my answer too simplistic, you should be adding more detail to your question.

How much code could be shared between each type of data handler?

It depends on how much commonality exists between each type of data. By commonality I mean the similarity in structure, or sub-structure.

For example, given that

Each PersonContactInfo contains one or more TelephoneContact record.

Each BusinessDepartmentContactInfo (also) contains one or more TelephoneContact record.

Then, if there is any code to be written for the TelephoneContact record, it can be reused between the two or more classes that uses it.

By similarity in structure, what I mean is not similarity in values or statistical distribution. I can point you to a counterexample.

Code reuse is applicable to all programming paradigms. Some paradigms and programming languages have specific syntax and library features to help with code reuse.

Choosing a programming paradigm for your problem.

The decision of what programming paradigm to use should come after:

You understand the size of data (order of magnitude) that you intend to handle.

If you need to handle billions of data, you may need to consider alternative paradigms, such as data-oriented design, database, or distributed processing.

You have a basic outline of what functionality needs to be in the software, but without going into too much detail.

You have a outline / preliminary plan of how you want your software to be structured.

A very useful technique is "CRC card", which stands for Class, Responsibility and Collaboration. It can be used for both object-oriented and non-object-oriented design.

You have identified the commonalities, as described above.

Deciding where to use POD (plain old data structure) or Objects.

If you have decided to use Java, it is recommended to use object-oriented design, as radarbob suggested above, because the advantage of using Java is lost if one do not take advantage of OOD.

It is assumed that you have finished with the Class-Responsibility-Collaborations step. In Object-oriented design, the result of CRC becomes your initial Java class design.

You can make further changes to your class design as you see fit, as in refactoring.

Writing code to read data from a file, and save results to a file.

There are many choices - so many that it is overwhelming.

At the minimum, a data reader needs to be implemented for the dataset format that is used by D1, D2, D3 and D4.

Java supports object serialization as part of its language.

However, if the source code of the class is modified, previously serialized data cannot be deserialized anymore - it will be lost.

Because this is a very prevalent issue, there are many solutions: (just to name a few)

https://stackoverflow.com/questions/17914197/serializing-objects-with-changing-class-source-code

http://my.safaribooksonline.com/book/databases/hadoop/9780596521974/serialization/id4397802

Also, you may consider the following trade-off:

Space efficient - take up as little disk space as possible - often means binary data and non-human-readable.

Human-readable - use text as much as possible (XML or JSON), but which takes up more disk space

Human-readable combined with standard compression, such as GZIP. This is a balanced approach between space and readability.

Should I use a database?

Unfortunately I do not have much experience with database. Other people can contribute ideas.


答:
Strictly in UML a decision node has only 1 input and a merge node only has 1 output. So in order to model a point with several inputs and outputs, you would need to have a merge node and then a decision node.

For example, at the top decision point of your diagram you would have a merge node to merge in the flows from the previous activity, and the repeat loop. This would have one output, to a decision node which then branches into the 4 different activities.

You could then have something similar at the bottom decision point: a merge node to merge in the 4 activites, which is followed by a decision node ([repeat] / [finished]) that branches (a) to the next part of the diagram and (b) to the repeat loop.

Then again, if you don't need to stick to strict UML, it might look cleaner if you bend the rules, as per RushPL's answer.

Title: Activity diagram, can merge node have more than 1 output?

Body:
There is a simple system, that allows users to do 4 things: ADD, EDIT, DELETE, PRINT data.

I am due to model it (I'm entirely new to UML activity diagrams) and from notation, I dont understand whether a decision node can have more than 3 inputs? It should be, otherwise how would I do that.

Anyway, the user can perform the action and do it again, so there is a loop needed. But the merge node is said to have only one output, which would not be the case.
The picture should be clear what I mean.


问:
Best way to define 'snap points' between two arbitrary objects in 3D?
I'm working on a simple in-browser 3D model constructor using THREE.js. The user picks a plane body, and adds wings, cockpit, tail etc of their choice, choosing from multiple options. I need to be able to define relationships between many bodies and many add-ons, and of course I don't want to manually have to define the position/rotation of each combination of parts. Therefore, I want to be able to define a set of 'snap points' on the body, places where certain components may be inserted, and to define a matching set of points on the add-on parts, basically matching the two in software to position the add-ons correctly.

I though of defining a triangle of 3 points, as that would lock in all 3 degrees of freedom. If I make the order important, it will even prevent the object from "flipping" across the plane defined by the three points. Here's an illustration:

I'm thinking of making a "dummy" for the 3D designers to use to get the coordinates of the points, but once case I can see this failing is when the two triangles don't exactly correspond to each other. Should I simply set in stone that the points must form an equilateral triangle of side length 10 units for example, or is there another way I could do the maths from triangles which do not completely match?

Perhaps there's another, more standard way to do what I want?

Thanks

答:
I'm going with the following.

This system relies on the snap points (in the sense of point=place, not a 3D point) being a group of 3 points arranged in an equilateral triangle. To avoid confusion, these triangles will be called snap hooks. A core may have an arbitrary number of snap hooks, each with its own ID. A module may only have one snap hook, the point with which it attaches to the core.

The snap hooks are specified with the points defined in a clockwise order. This order is important, as it defines the normal alignment of the snap hooks. It is suggested that the triangles be equilateral with a side length of 10mm. However, any triangles are supported, as defined in the algorithm.

(Throughout this, the core remains stationary. The module is moved so as to match the corresponding snap point on the core.)

Two planes are calculated, 1,the plane defined by the 3 points of the core snap point, and 2, the plane defined by the module’s snap point. A normal vector is calculated for each according to the right-hand rule.

The module is moved so that 1 = 2, that is so that the two snap hooks are coplanar, and that the two normal vectors are in opposing directions (facing each other).

The module is moved so that the centre point of its snap hook is incident on the centre point of the core’s snap hook. (At this point, only one degree of freedom remains – rotation around the axis going through the common centre point, perpendicular to the common plane.)

A line is calculated between the common centre point and vertex 1 of the core snap hook. The module is rotated so that the line between the common centre and vertex 1 of the module snap hook is collinear with this line, bringing the core and the module into alignment.


问:
How to solve this problem- Neural Net? Fuzzy? Other?
Hi I have a programming problem that I would like to solve using some artificial intelligence technique. I really dont know where to start. I would like some guidance as to what methodology to pursue.

Lets say I have 10,000 images of random people, and I need to detect elderly people in images. I might have algorithms like wrinkle detector, glasses detector, walking cane detector, missing teeth detector, skateboard detector, Playstation detector, etc. Each algorithm does a scan independently and outputs a number from 0 to 10 on the likelihood it thinks the image contains that item. Lets assume that works. There might be 100 different algorithms.

My set of 10,000 images would be divided by a human into two groups, those that contain an elderly person, and those that do not.

Now I need to develop a system that takes the series of values from the algorithm modules, when given an image to analyze, and calculates a single value that represents the likelihood that an image has elderly people in it or not.

During training I would like it to be able to automatically build rules by analyzing all the algorithms' outputs. For example:

If wrinkle detector, glasses detector, walking cane detector and missing teeth detector all output a high number, then output a high number.

If wrinkle, glasses, cane and teeth detectors are high, but playstation and skateboard detectors are also high, then output is neither low nor high.

hands detector and clothes detector should be essentially ignored as old and young people both have those (hopefully)

What type of technology should I be implementing for the automated rule building system?
Is this better solved by a neural network system?
A fuzzy logic system?
Something else?

Thanks for any advice.

答:
It sounds like this would be suitable for a neural network, probably a standard feedforward type.

I'm not sure how much you know about neural networks, but FYI the 'rules' it discovers won't be in a human-readable format. So if you want to run images through it and sort them, it'll do that; but if you're aiming to get a list of rules that you can see, you're probably better off choosing a different algorithm.

You mention in a comment you'd like to see which detectors are not contributing much. After the network is trained, you can look at the weights and see which inputs aren't doing much. Alternatively I believe there are some variations of neural networks that can automatically prune inputs; not my area of knowledge but worth looking into.

I should mention that neural networks can be fiddly, there's always a chance that they won't do what you expect, but from what I can see in this case it's very likely to work.


答:
Have a Look in ada boost (adaptative booster). The idea is to use independent weak classifier (your detectors) and combine them in a clever way. It roughly goes like this:

It first tries to evaluate the different detectors to detect and use an optimal linear combination of them to classify the data.

It then tries to find another combination able to provide a better discrimination on the first pass' failure cases

It goes on like this for any number of passes you want

You then have n combination applied in cascade, which gives you a "boosted" version of your detectors. Each pass will be expressed as 0.25 * wrinkle - 0.1 * playstation + .... Now I think you need a lot of detectors for this method to shine.

See here for an example of face detection using adaboost.

Title: How to solve this problem- Neural Net? Fuzzy? Other?

Body:
Hi I have a programming problem that I would like to solve using some artificial intelligence technique. I really dont know where to start. I would like some guidance as to what methodology to pursue.

Lets say I have 10,000 images of random people, and I need to detect elderly people in images. I might have algorithms like wrinkle detector, glasses detector, walking cane detector, missing teeth detector, skateboard detector, Playstation detector, etc. Each algorithm does a scan independently and outputs a number from 0 to 10 on the likelihood it thinks the image contains that item. Lets assume that works. There might be 100 different algorithms.

My set of 10,000 images would be divided by a human into two groups, those that contain an elderly person, and those that do not.

Now I need to develop a system that takes the series of values from the algorithm modules, when given an image to analyze, and calculates a single value that represents the likelihood that an image has elderly people in it or not.

During training I would like it to be able to automatically build rules by analyzing all the algorithms' outputs. For example:

If wrinkle detector, glasses detector, walking cane detector and missing teeth detector all output a high number, then output a high number.

If wrinkle, glasses, cane and teeth detectors are high, but playstation and skateboard detectors are also high, then output is neither low nor high.

hands detector and clothes detector should be essentially ignored as old and young people both have those (hopefully)

What type of technology should I be implementing for the automated rule building system?
Is this better solved by a neural network system?
A fuzzy logic system?
Something else?

Thanks for any advice.


问:
How to refactor an OO program into a functional one?
I'm having difficulty finding resources on how to write programs in a functional style. The most advanced topic I could find discussed online was using structural typing to cut down on class hierarchies; most just deal with how to use map/fold/reduce/etc to replace imperative loops.

What I would really like to find is an in-depth discussion of an OOP implementation of a non-trivial program, its limitations, and how to refactor it in a functional style. Not just an algorithm or a data structure, but something with several different roles and aspects - a video game perhaps. By the way I did read Real-World Functional Programming by Tomas Petricek, but I'm left wanting more.

答:
You would probably have to turn all your code inside out since OOP and FP have two opposite approaches to organizing code.

OOP organizes code around types (classes): different classes can implement the same operation (a method with the same signature). As a result, OOP is more appropriate when the set of operations does not change much while new types can be added very often. For example, consider a GUI library in which each widget has a fixed set of methods (hide(), show(), paint(), move(), and so on) but new widgets could be added as the library is extended. In OOP it is easy to add a new type (for a given interface): you only need to add a new class and implement all its methods (local code change). On the other hand, adding a new operation (method) to an interface may require changing all the classes that implement that interface (even though inheritance can reduce the amount of work).

FP organizes code around operations (functions): each function implements some operation that can treat different types in different ways. This is usually achieved by dispatching on the type via pattern matching or some other mechanism. As a consequence, FP is more appropriate when the set of types is stable and new operations are added more often. Take for example a fixed set of image formats (GIF, JPEG, etc) and some algorithms that you want to implement.
Each algorithm can be implemented by a function that behaves differently according to the type of the image. Adding a new algorithm is easy because you only need to implement a new function (local code change). Adding a new format (type) requires modifying all the functions you have implemented so far to support it (non-local change).

Bottom line: OOP and FP are fundamentally different in the way they organize code, and changing an OOP design into a FP design would involve changing all your code to reflect this. It can be an interesting exercise, though. See also these lecture notes to the SICP book cited by mikemay, in particular slides 13.1.5 through 13.1.10.


问:
Rich Domain Models -- how, exactly, does behavior fit in?
In the debate of Rich vs. Anemic domain models, the internet is full of philosophical advice but short on authoritative examples.  The objective of this question is to find definitive guidelines and concrete examples of proper Domain-Driven Design models. (Ideally in C#.)

For a real-world example, this implementation of DDD seems to be wrong:

The WorkItem domain models below are nothing but property bags, used by Entity Framework for a code-first database.  Per Fowler, it is anemic.

The WorkItemService layer is apparently a common misperception of Domain Services; it contains all of the behavior / business logic for the WorkItem. Per Yemelyanov and others, it is procedural. (pg. 6)

So if the below is wrong, how can I make it right?

The behavior, i.e. AddStatusUpdate or Checkout, should belong in the WorkItem class correct?

What dependencies should the WorkItem model have?

```<code>public class WorkItemService : IWorkItemService {
    private IUnitOfWorkFactory _unitOfWorkFactory;

    //using Unity for dependency injection
    public WorkItemService(IUnitOfWorkFactory unitOfWorkFactory) {
        _unitOfWorkFactory = unitOfWorkFactory;
    }

    public void AddStatusUpdate(int workItemId, int statusId) {

        using (var unitOfWork = _unitOfWorkFactory.GetUnitOfWork<IWorkItemUnitOfWork>()) {
            var workItemRepo = unitOfWork.WorkItemRepository;
            var workItemStatusRepo = unitOfWork.WorkItemStatusRepository;

            var workItem = workItemRepo.Read(wi => wi.Id == workItemId).FirstOrDefault();
            if (workItem == null)
                throw new ArgumentException(string.Format(@"The provided WorkItem Id '{0}' is not recognized", workItemId), "workItemId");

            var status = workItemStatusRepo.Read(s => s.Id == statusId).FirstOrDefault();
            if (status == null)
                throw new ArgumentException(string.Format(@"The provided Status Id '{0}' is not recognized", statusId), "statusId");

            workItem.StatusHistory.Add(status);

            workItemRepo.Update(workItem);
            unitOfWork.Save();
        }
    }
}
</code>```

(This example was simplified to be more readable. The code is definitely still clunky, because it's a confused attempt, but the domain behavior was: update status by adding the new status to the archive history. Ultimately I agree with the other answers, this could just be handled by CRUD.)

Update

@AlexeyZimarev gave the best answer, a perfect video on the subject in C# by Jimmy Bogard, but it was apparently moved into a comment below because it didn't give enough information beyond the link.  I have a rough draft of my notes summarizing the video in my answer below.  Please feel free to comment on the answer with any corrections. The video is an hour long but very worth watching.

Update - 2 Years Later

I think it's a sign of DDD's nascent maturity that even after studying it for 2 years, I still can't promise that I know the "right way" of doing it. Ubiquitous language, aggregate roots, and its approach to behavior-driven design are DDD's valuable contributions to the industry. Persistence ignorance and event sourcing causes confusion, and I think philosophy like that holds it back from wider adoption. But if I had to do this code over again, with what I've learned, I think it would look something like this:

I still welcome any answers to this (very active) post that provide any best-practices code for a valid domain model.

答:
Your assumption that encapsulating your business logic associated with WorkItem into a "fat service" is an inherent anti-pattern which I would argue is not necessarily.

Regardless of your thoughts on the anemic domain model, the standard patterns and practices typical of a Line of Business .NET application encourage a transactional layered approach comprised of various components. They encourage the separation of business logic from the domain model specifically to facilitate communication of a common domain model across other .NET components as well as components on different technology stacks or across physical tiers.

One example of this would be a .NET based SOAP web service that communicates with a Silverlight client application that happens to have a DLL containing simple data types.  This domain entity project could be built into a .NET assembly or a Silverlight assembly, where interested Silverlight components that have this DLL will not be exposed to object behaviours that may be dependent on components only available to the service.

Regardless of your stance on this debate, this is the adopted and accepted pattern put forth by Microsoft and in my professional opinion it is not a wrong approach but then an object model that defines its own behaviour is not necessarily an anti-pattern either.  If you go forward with this design it is just best to realize and understand some of the limitations and pain points that you might run into if you need to integrate with other components that need to see your domain model.  In that particular case perhaps you may want to have a Translator convert your object oriented style domain model into simple data objects that do not expose certain behaviour methods.

OwnerDisplayName: RJB


问:
Pure Java web browser, is it practical?
I know that a Java web browser is possible, but is it practical? I've seen the Lobo project and must admit I am impressed, but from what I've gathered it seems that development stopped in 2009. Would a browser coded in pure Java (no WebKit java bindings of any type) be able to compete with those among the ranks of Chrome or Firefox, or would it be inherently slower, hindering the user?</p>

答:
It would be comparable to the concept in the Windows 9x days of running software OpenGL vs hardware-accelerated OpenGL. The problem with using Java for something like a web-browser is that you potentially use many extra clock-cycles to do something that may be possible in many-fewer in a more-native language. That was the concept with OpenGL as well - you could complete the task but it took much more processing to do it.

So, is it possible? Potentially. Would it be competitive? Unlikely - something in highly-optimized, platform-dependent code is likely going to have a significant speed advantage.

This is merely speculation though.

Title: Pure Java web browser, is it practical?


问:
How much logic can be put into an object-pooling factory class before it does more harm than good?
The main language I'm interested in doing object pooling in is AS3, which is known to need it in many cases.  In the past I've always made a brand new factory class for every type I was going to try to pool, the parameters of its "object-producing" function being the same as those of that type's constructor.  Essentially:

```<code>static public function produce(<list of paramaters>):<type>
{
    if (m_arryPool.length)
    {
        var obj:<type> = m_arryPool.pop();
        // do something with the arguments passed to produce()
        return obj;
    }
    return new obj(<arguments passed to produce()>);
}
</code>```

But recently I've been trying to think of a way to avoid re-writing this sort of boiler-plate code for every single type I want to pool, but probably without forfeiting the idea of passing arguments around to the returned objects as in the above example, and definitely without putting so much dynamic functionality and stuff in there that it just winds up slowing stuff down too much.

I'm still a little green at object-pooling.  I know a one-size-fits-all pooling factory will probably not work out in all cases (AS3's Function.apply(), for instance, doesn't support constructors), but when does it get to the point that you're just passing in so many arguments to the produce() function, using so many untyped variables, going through so many dictionaries and lists, etc., that it just isn't hardly worth it anymore?

I know this question may be slightly subjective, but I do believe there are largely objective answers to it.  I'm mainly interested in how this would apply to AS3, but I'm also interested in (and asking for) a general answer.  Is the best way to handle it generally just to go ahead and write boilerplate code for every type you plan to pool or something like that?  Thanks!

答:
I don't know AS3, but I can offer you some design advice.  If you are passing in so many arguments, you might want to rethink your design.

Why not seperate the creation and initialization?  You pass in one argument which would be the type id of the object that you need.  Each class has its own static type id to represent it, and you access it by calling something like getID().

You use the type id as a hash or index into the object pool to get the object.  The pool for each object is contained within 1 dynamic array index by the type id.

The type id is used as the method to determine the object.  In a seperate function, such as the calling function, you call a function on the object to initialize the object.

No matter what you decide, you should stress test AC3 to set appropiate limits in your code before you go live with a solution.


问:
How can web development bootcamps deliver on their promise?
I came across the concept of web development bootcamps, these 9-10 week intensive crash courses claim to teach beginners web development and help them get 80k starting salary jobs. Many of you might have heard of these.

Is what the bootcamps promise feasible? Is it possible for web technologies like Ruby on Rails, HTML5, CSS, and Javascript to be taught from scratch in such a short period? And to people without a technical background?

答:
I am in a 'bootcamp' style ruby program currently and I can tell you a few things.

The length of the program matters. As does the stated intent. Our program is six months, fulltime intensive. Even still, from the beginning we're told exclusively that what we are learning is to be a good employee - we will be employees with good habits and best practices drilled into our heads - NOT master programmers.

The guaranteed salary is legit. IF the school is legit.
The class before us had a success rate of 25 out of 26 students getting higher that 60,000 a year jobs. Most much higher. But our program has a stellar reputation and the professors are well known and liked, so the jobs came from their personal introductions

Can you teach someone without a development background?
Yes. Half of our class has no background. That said, there are a BUNCH of tutorials online and if you are not the kind of person who was so interested in programming that you didn't dabble in them before you attended the bootcamp... you probably have a few other barriers to being a programmer that you should look at first.

Personally, I think a short bootcamp is only a good option if you have already worked very hard to attend MeetUps, work through tutorials, read about the language and work with other programmers to learn basics.
The reason you want to attend a class is to learn the things that are harder to read about - like how to pair, what good manners are in the community, etc... and to build a network of students and teachers.
So I would take a long, hard look at the reputations of the graduates and administration of those bootcamps. In the ruby world, that's pretty easy to do with github and twitter!


问:
s expression representation for c
Experimenting with various lisps lately  (clojure especially) i have wondered if there are any s expression based representations of (subsets) of c, so you could use lisp/closure to write macros and then convert the s-expression c tree to pure c.

I am not asking for a to-c-compilers of lisp/scheme/clojure but more of using lisps to transform a c syntax tree.

Little background to why i am asking this question: i find myself to really enjoy certain clojure macros like the threading macros -> doto etc. And i feel that they would be great in a non FP  environment as well.

答:
You can get this from any AST representation of a C program.  Just walk the tree and dump it as an S-expression.  All you need now is a good C parser that will build an AST.

I understand you can bend GNU to do that.  I don't know how.

There are tools that can export XML versions of the AST, which are trivially equivalent to S-expressions.  Our DMS Software Reengineering Toolkit it one of these.  It can even retain some of the preprocessor directives.  Not a dump of C, but a dump of Java doing exactly the same thing  can be found here.

What you will find a bit harder is to regenerate valid source text from the tree.  If you can't do that, doing transformations on the tree seems pointless.

You wanted to do this to apply transformations to the C code.  Yes, you can do with with tree operations in lisp relatively easily.  But you have code those transformations in lisp.  DMS provides the ability to carry out transformations, using the surface syntax of the language (e.g., transfomations written using C syntax for patterns).  That makes them generally easier to write, because the surface syntax doesn't have to know the microscopic detail of the AST.  (DMS also has built-in prettyprinting of the trees).

Title: s expression representation for c


问:
Is it ok to learn from C# 2002 materials?
I've found some videos that explain C# but it back to C#.NET when it is first appeared, if I learn from these videos will I learn something that has been removed from the language? will I miss alot? </p>

答:
Absolutely!

There's absolutely nothing stopping you from learning later revisions of the language specification, but by learning from C# 2.0 - you'll get a much better idea of what features are available in each version of the language.

It's worth stressing that the language and the .NET framework are seperate things, and both change between releases of Microsoft's .NET distribution. A great example of this is: in .NET 2.0 we only have WinForms for GUI, however in later releases there are WPF and Silverlight.

Knowing the difference between the language and framework features in different releases is important - if you're targeting the compact runtime or Novell's cross-platform Mono runtime, they only support specific features - knowing your way around is good.

If you're looking for a more 'mainstream' example - many enterprises will only have a specific .NET runtime available as part of their server SOE, so custom developed and industry-specific software usually needs to be written to support older versions of the Microsoft release!

It's still important to be up to date, but at the end of the day - the person with the better holistic understanding of the technology they're using (versus someone who only understands what is the current fashion) is going to do better in the long run.

Hope this helps :)

ContentLicense: CC BY-SA 2.5


问:
Test Driven Development: A good/accepted way to test file system operations?
I am working on a project at the moment that generates a table (among other things) based on the contents of a file-system, and in turn does some meta-data modifications on the things it finds.  The question is: how should tests be written around this, or set up?  Is there an easy way to mock this out? Or should I setup a "sandbox"?</p>

答: As you do always in TDD with external resources: you create one or more interfaces to your filesystem operations and "mock them out". You want to test your "table generator" and your meta-data modification code, not the file system operations itself (most probably you are using ready-made library implementations for accessing the file system).</p>


答:
Your question cannot be answered, because your example is wrong. Specifically, because there is no behavior. At least not in area of your domain. The example of AddStatusUpdate method is not a domain logic, but logic that uses that domain. That kind of logic does make sense to be inside some kind of service, that handles outside requests.

For example, if there was requirement that a specific work item can have only specific statuses, or that it can only have N statuses, then that is domain logic and should be part of either WorkItem or StatusHistory as a method.

The reason for your confusion is because you are trying to apply a guideline to code that doesn't need it. Domain models are only relevant if you have lots of complex domain logic. Eg. logic that works on entities themselves and stems from requirements. If the code is about manipulating entities from outside data, then that is not, most probably, a domain logic. But the moment you get lots of ifs based on what data and entities you are working with, then that is domain logic.

One of the problems of true domain modeling is that it is about managing complex requirements. And as such its true power and benefits cannot be showcased on simple code. You need dozens of entities with tons of requirements around them to truly see the benefits. Again, your example is too simple for domain model to truly shine.

Finally, some OT thing I would mention is that a true domain model with real OOP design would be really hard to persist using the Entity Framework. While ORMs were designed with mapping true OOP structure to relational ones, there are still many problems, and the relational model will often leak into the OOP model. Even with nHibernate, which I consider much more powerful than EF, this can be a problem.

Title: Rich Domain Models -- how, exactly, does behavior fit in?

Body:
In the debate of Rich vs. Anemic domain models, the internet is full of philosophical advice but short on authoritative examples.  The objective of this question is to find definitive guidelines and concrete examples of proper Domain-Driven Design models. (Ideally in C#.)

For a real-world example, this implementation of DDD seems to be wrong:

The WorkItem domain models below are nothing but property bags, used by Entity Framework for a code-first database.  Per Fowler, it is anemic.

The WorkItemService layer is apparently a common misperception of Domain Services; it contains all of the behavior / business logic for the WorkItem. Per Yemelyanov and others, it is procedural. (pg. 6)

So if the below is wrong, how can I make it right?

The behavior, i.e. AddStatusUpdate or Checkout, should belong in the WorkItem class correct?

What dependencies should the WorkItem model have?

```<code>public class WorkItemService : IWorkItemService {
    private IUnitOfWorkFactory _unitOfWorkFactory;

    //using Unity for dependency injection
    public WorkItemService(IUnitOfWorkFactory unitOfWorkFactory) {
        _unitOfWorkFactory = unitOfWorkFactory;
    }

    public void AddStatusUpdate(int workItemId, int statusId) {

        using (var unitOfWork = _unitOfWorkFactory.GetUnitOfWork<IWorkItemUnitOfWork>()) {
            var workItemRepo = unitOfWork.WorkItemRepository;
            var workItemStatusRepo = unitOfWork.WorkItemStatusRepository;

            var workItem = workItemRepo.Read(wi => wi.Id == workItemId).FirstOrDefault();
            if (workItem == null)
                throw new ArgumentException(string.Format(@"The provided WorkItem Id '{0}' is not recognized", workItemId), "workItemId");

            var status = workItemStatusRepo.Read(s => s.Id == statusId).FirstOrDefault();
            if (status == null)
                throw new ArgumentException(string.Format(@"The provided Status Id '{0}' is not recognized", statusId), "statusId");

            workItem.StatusHistory.Add(status);

            workItemRepo.Update(workItem);
            unitOfWork.Save();
        }
    }
}
</code>```

(This example was simplified to be more readable. The code is definitely still clunky, because it's a confused attempt, but the domain behavior was: update status by adding the new status to the archive history. Ultimately I agree with the other answers, this could just be handled by CRUD.)

Update

@AlexeyZimarev gave the best answer, a perfect video on the subject in C# by Jimmy Bogard, but it was apparently moved into a comment below because it didn't give enough information beyond the link.  I have a rough draft of my notes summarizing the video in my answer below.  Please feel free to comment on the answer with any corrections. The video is an hour long but very worth watching.

Update - 2 Years Later

I think it's a sign of DDD's nascent maturity that even after studying it for 2 years, I still can't promise that I know the "right way" of doing it. Ubiquitous language, aggregate roots, and its approach to behavior-driven design are DDD's valuable contributions to the industry. Persistence ignorance and event sourcing causes confusion, and I think philosophy like that holds it back from wider adoption. But if I had to do this code over again, with what I've learned, I think it would look something like this:

I still welcome any answers to this (very active) post that provide any best-practices code for a valid domain model.


答: Create a wrapper for the file system operations. In the tests, pass in a mock that implements the same interface as the wrapper. In production, pass in the wrapper.</p>

Title: Test Driven Development: A good/accepted way to test file system operations?

Body: I am working on a project at the moment that generates a table (among other things) based on the contents of a file-system, and in turn does some meta-data modifications on the things it finds.  The question is: how should tests be written around this, or set up?  Is there an easy way to mock this out? Or should I setup a "sandbox"?</p>


答:
Whats wrong with having a "test" file system?

Create a template folder/directory structure which has enough content to test you operations.

During setup of your unit test copy this initial structure (would recommend you ZIP up the template and unzip into your test area).
Run your tests.
Delete the whole thing during tear down.

The problem with mocking is firstly file systems, OSes and databases which belong to your project do not really qualify as external resources and secondly mocking low level system calls is both time consuming and error prone.


问:
Handling Server Response Timeouts
Consider the following scenario :

User sends a request to transfer money.

Server receives the request and transfers the money but the reply times out.

The app reports failure.

So the user tries to transfer money again.

How do we avoid this kind of a scenario ?

答:
There are two ways:

Make the operation idempotent, i.e. doing it twice has no different effect from doing it just once.

Make it possible to find out status of a request ex-post. That is, have additional query for result of past request given it's ID.

For protocols between applications the former is preferred, but you'll have to do the later when the user gets involved.

Basically when you don't get the response, you retry the request with the same ID and same one-time-password (or whatever authentication token that is different for each request to prevent replay attack) and make sure the server does nothing and repeats the last response if it has already seen the request. That will handle case when the network simply drops the response.

However when the network has longer outage just in the inconvenient moment, the user will eventually give up and close the app. Than when they start it again later you need a way to show them which transactions were received on server so they know whether they need to enter the transaction again or not. Because you've lost state by user closing the app, your only chance here is to list the transaction and make sure the user sees it.

Title: Handling Server Response Timeouts


问:
Best OOP design pattern for a sequence of operations
I am working on an application, a module of which does the following financial operations sequentially:

When a user requests for a certain amount to be transferred into her bank account:

check whether any transaction can happen now? (transaction can be carried out only during a certain time period)

check whether the user has requested for a minimum amount to be withdrawn

check whether the user has any default account

The result of all the above actions should be logged.

If all the above condition satisfies, the transaction is carried out. In future, there might be some additional checks.

Which object oriented design pattern should be best suitable for the above case?

答:
According to my understanding whatever is required can be fitted into the command pattern like below. Class design can be done as per below.

```<code>interface Transaction{
void performAction();
}

class Banking{

void moneyValidation(){
//Validate Here
}

void timeValidation(){
//validate Here
}
}

class TimeValidation implements Transaction{

public Banking bank;

public TimeValidation (Banking bnk){
bank=bnk;
}

void performAction(){
bnk.timeValidation();
}

class MoneyValidation Implements Transaction{

public Banking bank;

public MoneyValidation(Banking bnk;){
bank=bnk;
}

void performAction(){
bnk.moneyValidation();
}
}

class Control{

private List val_list=new ArrayList();

void storeValidation(Transaction trans){
val_list.add(trans);
trans.performAction(val_list.getFirstAndRemove());
}
}

//Same for other validation classes
</code>```

Your Client class will contain the following code snippet:

```<code>Banking bnk = new Banking();
MoneyValidation m_val = new MoneyValidation (bnk);
TimeValidation t_val = new TimeValidation (bnk);
Control ctrl = new Control();
ctrl.storeValidation(m_val);
ctrl.storeValidation(t_val);
</code>```

This is as per my understanding, with the scenario which has been given above.

Body:
According to my understanding whatever is required can be fitted into the command pattern like below. Class design can be done as per below.

interface Transaction{
void performAction();
}

class Banking{

void moneyValidation(){
//Validate Here
}

void timeValidation(){
//validate Here
}
}

class TimeValidation implements Transaction{

public Banking bank;

public TimeValidation (Banking bnk){
bank=bnk;
}

void performAction(){
bnk.timeValidation();
}

class MoneyValidation Implements Transaction{

public Banking bank;

public MoneyValidation(Banking bnk;){
bank=bnk;
}

void performAction(){
bnk.moneyValidation();
}
}

class Control{

private List val_list=new ArrayList();

void storeValidation(Transaction trans){
val_list.add(trans);
trans.performAction(val_list.getFirstAndRemove());
}
}

//Same for other validation classes

Your Client class will contain the following code snippet:

Banking bnk = new Banking();
MoneyValidation m_val = new MoneyValidation (bnk);
TimeValidation t_val = new TimeValidation (bnk);
Control ctrl = new Control();
ctrl.storeValidation(m_val);
ctrl.storeValidation(t_val);

This is as per my understanding, with the scenario which has been given above.


问:
Could we set priorities only relative to each other instead of fixed numbers?
AFAIK the lowest priority has the highest number in scheduling and in my system all priorities must be different. But isn't other policies thinkable? For instance, how about a policy where priorities are not numbers but say that a task's priority would be defined only in term of another task's priority, and that other task would be the closest in priority to the task whose priority we are setting. Then we would never use actual numbers for priorities, but we would keep a data structure sorting the tasks in priorities and when a task comes as new or is getting a different priority assigned, then this structure is rebalanced. Would this priority mechanism be feasible or do you not agree that it's a working idea? </p>

答:
In principle, the idea is good, and it solves a real problem: what do you do when the developers of two other programs have chosen priorities 12 and 11 for their processes and you need yours to be in between those two?

However, there's two problems:

You need to do a topological sort of the priority graph every time a new process is created or its priority is changed. The best known algorithm for doing an online topological sort has an amortized worst-case time complexity of something like O(√#edges). That means creating a process will get slower the more processes there are in your system. This is unacceptable, especially on systems like Unix and its cousins or Erlang, where a process is the basic unit of program decomposition, and you have thousands (Unix) or even tens of millions (Erlang) processes on a typical system.

You will only get a partial ordering. What do you do when there are two processes which could be scheduled but they don't have an ordering defined between them? Which one do you run first? In a totally different field, the Fortress programming language has a similar problem: Fortress doesn't have an operator precedence table, instead operator precedence is defined relative to other operators (e.g. + has same precedence as -, * has higher precedence than +) etc. In Fortress, mixing two operators which don't have a defined ordering is simply a compile error. But you can't really do that with two processes, simply refuse to start one.

On a "closed" system where the total set of potentially running processes is fully known before runtime at development time, you could do all of the work of making sure the ordering is total, detecting cycles in your graph, and topologically sorting at development time. And in fact, that's what's typically done when developing hard-realtime systems.


问:
What are some things you have read that inspired and guided you as a programmer?
For example, being a beginner, I find a lot of inspiration and direction from reading this post by Bryan Woods.</p>

答:
As a teenager, I read translations of articles from Dave Small (*) in an Atari ST-related magazine and his writings were very inspiring to me. This guy was having fun solving tricky problems, not working for a big company but for his own and had great advice about people. People matter, not technology!

(*) Or David Small, from Gadgets by Small who emulated a Mac on an Atari.


问:
Abstracting user interface from domain
My course text suggests creating a 'facade' class to completely abstract the user interface from the domain layer. That is, the UI uses only basic types, and if it needs a reference to a domain object, it only knows it as an Object.

To give you an idea, this is what it might look like (example in Java but could equally apply to other languages):

```<code>public class Facade
{
    ...
    public Object getLastOrder(Object customer)
    {
        Customer castCustomer = (Customer)customer;
        Order lastOrder = domainController.getLastOrder(castCustomer);
        return lastOrder;
    }
}
</code>```

Note: I'm not sure whether this is in fact a type of facade pattern (I've heard it defined differently elsewhere), but I don't want to get too bogged down in terminology.

Compared to nothing (having the UI call the domain controller directly), I can see that this has the advantage that the UI is much more independent of changes to the domain model implementation. There's always a risk that very major changes (such as not having anything representing an order any more) will break things, but this seems to be able to absorb anything else.

However, it seems to sacrifice type checking, and it means that getting even simple properties of domain objects more convoluted than it needs to be (anOrder.getNumber() vs facade.getOrderNumber(anOrder)).

My own thought was that it would be better for the UI to reference domain objects in terms of interfaces, rather than plain Objects. For example:

```<code>public class Facade
{
    ...
    public IOrder getLastOrder(ICustomer customer)
    {
        Customer castCustomer = (Customer)customer;
        Order lastOrder = domainController.getLastOrder(castCustomer);
        return lastOrder;
    }
}
</code>```

or even if the domain controller itself exposed only the interface types, forgetting the 'facade' altogether.

As far as I can see, this is better from a type checking point of view. Major changes (e.g. removing Order from the system) can break things, but that was true of the 'plain Object' solution.

And any methods that are stable (e.g. anOrder.getNumber()) can be specified in the interfaces, so calling them from the UI is simpler and more object-orientated. Obviously this only applies to methods whose signatures are stable, to avoid breaking the UI, but the implementation is still free to change.

Is there something I'm missing? Does my 'interface' solution have any drawbacks I haven't spotted? Or is there a completely different, better solution that I haven't though of?

答:
Advantage of the first version:

your API won't change, and it will be super-stable as it cannot be more general: public Anything DoSomething(Anything something) { }

Disadvantage:

the caller should always guess and cast your return value. What if the developer won't check your documentation and does this:

if ((bool)yourObject.getLastOrder(customer)) { ... }

you are where you are started: both the caller and the function depends on the Customer concrete class. It is just hidden from the signature, so you introduce a new level of failure: what happens when you write the following totally logical code:

Company theirCompany = MyDb.GetCompany(12345);
Order order = (Order)yourObject.getLastOrder(theirCompany);

You still have to check every single call if Customer class changes. You made matter worse by replacing all concrete types with object. There is a level when you cannot be more abstract and you are making more work for yourself.

If you have a program for handling orders you cannot prepare it to make only very little changes where you are not handling orders anymore... But you can prepare if there will be new types of orders and customers.

Given that, the only useful level of abstraction you can have here is to find out what is the minimal amount of information you need in your function/class about getting an order.

So, you slicing that information from your ICustomer interface. For orders you'll have, say, an ICustomerID interface:

```<code>public interface ICustomerID { int getID(); }

public interface ICustomer : ICustomerID { ... }

public interface ICompany : ICustomerID { ... }
</code>```

So back to your function:

```<code>public IOrder getLatestOrder(ICustomerID id) { /* get order */ }
</code>```

And calling would look like this:

```<code>Customer customer = SomeFactory.GetCustomer(...);
Company company = SomeOtherFactory.GetCompany(...);

IOrder customerOrder = myObject.getLatestOrder(customer);
IOrder companyOrder = myObject.getLatestOrder(company);
</code>```

You can have two totally different interface for Customer and Company; you can change their implementations any time; you won't have to change getLatestOrder.

Title: Abstracting user interface from domain

Body:
Advantage of the first version:

your API won't change, and it will be super-stable as it cannot be more general: public Anything DoSomething(Anything something) { }

Disadvantage:

the caller should always guess and cast your return value. What if the developer won't check your documentation and does this:

if ((bool)yourObject.getLastOrder(customer)) { ... }

you are where you are started: both the caller and the function depends on the Customer concrete class. It is just hidden from the signature, so you introduce a new level of failure: what happens when you write the following totally logical code:

Company theirCompany = MyDb.GetCompany(12345);
Order order = (Order)yourObject.getLastOrder(theirCompany);

You still have to check every single call if Customer class changes. You made matter worse by replacing all concrete types with object. There is a level when you cannot be more abstract and you are making more work for yourself.

If you have a program for handling orders you cannot prepare it to make only very little changes where you are not handling orders anymore... But you can prepare if there will be new types of orders and customers.

Given that, the only useful level of abstraction you can have here is to find out what is the minimal amount of information you need in your function/class about getting an order.

So, you slicing that information from your ICustomer interface. For orders you'll have, say, an ICustomerID interface:

public interface ICustomerID { int getID(); }

public interface ICustomer : ICustomerID { ... }

public interface ICompany : ICustomerID { ... }

So back to your function:

public IOrder getLatestOrder(ICustomerID id) { /* get order */ }

And calling would look like this:

Customer customer = SomeFactory.GetCustomer(...);
Company company = SomeOtherFactory.GetCompany(...);

IOrder customerOrder = myObject.getLatestOrder(customer);
IOrder companyOrder = myObject.getLatestOrder(company);

You can have two totally different interface for Customer and Company; you can change their implementations any time; you won't have to change getLatestOrder.


问:
How could distribution and reuse flexibility be hurt by linking my program as a static or dynamic library?
I'm writing a small program that I want to be able to link with other programs.  I also intend to run it from a command line interface, and maybe later with a GUI interface.

How could distribution and reuse flexibility be hurt by linking my program as a static or dynamic library?

Distribute it as a library and

Dynamically link for GUI and command line interfaces

Statically link for a stand alone binary

答:
I know this is a bit late in the day, but thought I would throw my tuppence in:
In regards to which is best it really is a very subjective matter, depending greatly on what functionality, security, availability and security you require:
With dynamic linking, for example:

save memory: multiple programs can access your DLL functionality simultaneously

Independence: any language that can access a DLL can utilise the functionality you have loving crafted

versioning/locale: you can make locale or version specific dlls or even a single dll which can contain version/locale specifics, without worrying about changes to the program, the dll will do it all for you (well onceyou have put in the work to start with...Nothing is free:)

save disk space: one DLL on disk can serve throughout a system

upgrade ease: you can upgrade a whole set of functionality with a simple DLL change

With static linking you can:

ensure your program Always has the functions available within the SLL

ahem optimally use your disk space: well, the executable will be bigger, however, chances are that by trading off some disk space you will have a much(variable amount of much-ness) faster program

distribution: much easier as you will have reduced or non-extant dependencies, so no extra files to include, just to achieve some functionality.  The executable will contain all the SLL code and that's it, all you will need are any resources you want to include seperately from an SLL.

security:  if everything your program needs is statically linked then your exe will be that bit harder to hack or crack, although nothing can stop a truly determined security breacher, size and complexity can often dissuade amateurs and tinkerers.  Obviously obfuscation helps too.

There are other reasons too, but as an initial breakdown of the pros of each I thought this may help anyone else looking at the question.


问:
c++ web with nginx - Do I have to worry about thread safety?
I am currently developing my website with c++. I know that nginx handles connections with multiple threads to provide high performance. And not all c++ code is thread safe.

What's the relationship between nginx's multithreading and c++ application's multithreading?

Do I have to worry about this?

What should I do to avoid possible issues?

答:
I assume you are using nginx as a reverse proxy. In such case any parallel connections that come to you app are queued by operating system. You should not even count nginx in your equation because you can never predict when a connection comes. What you control though is the moment of accepting/handling it.

Truth is that usually listening for connections is handled in a single thread, in some kind of a loop. It is the handling part may or may not be done in a multi-threaded.

The simple and safe design below.

With such approach there is no need to worry about multiple threads. If a different connection comes in the middle of handling the first one then it will simply be queued and have to wait.

You can improve this if you write your app in a way that the relevant state is stored in a separate entity/database and then you may simply start several single-threaded C++ processes.

If you fork your C++ process or use a FastCGI backend you may share a single listening socket that will dispatch the incoming connections to several single-threaded C++ app instances.

I would strongly advice a multi-process approach due to the "leaky" and "crashy" nature of C++. If you have multiple processes any one of them may be restarted and / or crash without compromising the whole system.

Incidentally you get thread-safety by design if handling only one connection at a time by a process. This would mimic Node.JS web servers which have a reputation for being snappy.


答:
I would advise you to use viewmodel classes for your UI instead of domain objects. There tends to be a large difference between the representation of data that your view needs and the representation of data that the domain needs.

Say you want to show a list of orders in the UI. An Order in the domain will probably have a lot of properties, some reference objects, etc. You'll probably not need most of those things in the UI, so just take what you do need, shove it into a viewmodel and bind that viewmodel to the UI.

PS: a facade is used to simplify working with one or more objects. If you want to achieve something and to do that, you'd have to make 5 calls to 5 different objects, a facade's responsibility would be to encapsulate those 5 calls, shielding you from the complexity of working with those 5 different objects.

Title: Abstracting user interface from domain

Body:
My course text suggests creating a 'facade' class to completely abstract the user interface from the domain layer. That is, the UI uses only basic types, and if it needs a reference to a domain object, it only knows it as an Object.

To give you an idea, this is what it might look like (example in Java but could equally apply to other languages):

```<code>public class Facade
{
    ...
    public Object getLastOrder(Object customer)
    {
        Customer castCustomer = (Customer)customer;
        Order lastOrder = domainController.getLastOrder(castCustomer);
        return lastOrder;
    }
}
</code>```

Note: I'm not sure whether this is in fact a type of facade pattern (I've heard it defined differently elsewhere), but I don't want to get too bogged down in terminology.

Compared to nothing (having the UI call the domain controller directly), I can see that this has the advantage that the UI is much more independent of changes to the domain model implementation. There's always a risk that very major changes (such as not having anything representing an order any more) will break things, but this seems to be able to absorb anything else.

However, it seems to sacrifice type checking, and it means that getting even simple properties of domain objects more convoluted than it needs to be (anOrder.getNumber() vs facade.getOrderNumber(anOrder)).

My own thought was that it would be better for the UI to reference domain objects in terms of interfaces, rather than plain Objects. For example:

```<code>public class Facade
{
    ...
    public IOrder getLastOrder(ICustomer customer)
    {
        Customer castCustomer = (Customer)customer;
        Order lastOrder = domainController.getLastOrder(castCustomer);
        return lastOrder;
    }
}
</code>```

or even if the domain controller itself exposed only the interface types, forgetting the 'facade' altogether.

As far as I can see, this is better from a type checking point of view. Major changes (e.g. removing Order from the system) can break things, but that was true of the 'plain Object' solution.

And any methods that are stable (e.g. anOrder.getNumber()) can be specified in the interfaces, so calling them from the UI is simpler and more object-orientated. Obviously this only applies to methods whose signatures are stable, to avoid breaking the UI, but the implementation is still free to change.

Is there something I'm missing? Does my 'interface' solution have any drawbacks I haven't spotted? Or is there a completely different, better solution that I haven't though of?


问:
Are Nested Static Library dependencies possible?
I am working in QT .

Can a static library depend on another static library?(Static Lib is made by linking another static lib)

If yes, is it possible that after linking to  lib2, the generated lib(lib1) would not contain all the codes of lib2?

In my Qt Project I am using a static library, which depends on multiple libraries. I had to add all the libraries (with all their headers in my project), although I need only one lib (and one .h of that class) in my code.

Please explain the scenario.

答:
My quick two bits on this: 10 (sorry terrible joke).

To expand slightly, here goes:

1- A static library can depend on another static library, nothing or even a dynamic library: in the first two instances all the code for the new static library would be incorporated in the new SLL (Static Link Library), however, the 3rd option, depending on evironment could lead to the SLL having one of the following outcomes,

it would contain static versions of the code required by it gathered from the DLL (Dynamic Link Library)

or, much more horribly, you would have a static library that when included in a project would cause the requirement of shipping with a DLL , breaking the whole point of static linking.

So in short yep, you can link a static library to a static library

2- if lib1 and lib2 are both static, and lib1 has been linked with lib2, then all the functionality of lib2 would be available within lib1 without the need to include lib2 as lib2 would be statically linked within lib1  (think russian dolls, with lib2 being the smaller).

In the scenario you describe there must be discrete functionality available in each of the files you are having to include, which is not statically linked, hence the need for multiple files, otherwise you would have a single file to include and you would be fine.

Take the following:
One .h file with references to 6 statically linked libraries:  you would need to include 7 files in your project to get full functionality

One SLL which was created from said .h File would require only the new SLL to be included for linking at compilation:

Hope this helps and that I have understood what you were asking.

ContentLicense: CC BY-SA 4.0


答:
While the patterns are already mentioned here, i would suggest you to think about how you would like to use the same in your application, based on the frameworks you are using.

For instance, the validation you would like to do, most likely will keep changing as and when time progress (may be you want to add a new validation in future which restricts transactions to 10 a day). Also, you may not want to do the validation before your actual business service or integration code kicks in.
It would be good, if you can have the validations added as configurable ones.

In case you are using Struts, using interceptors might be a good idea. In case of spring, beans injection as dependency gives you more flexibility.
My suggestion is not only to look at the patterns/idioms but also look at the framework which you use to build the application and see how best you can fit in your requirement from a futuristic point of view.

Title: Best OOP design pattern for a sequence of operations

Body:
I am working on an application, a module of which does the following financial operations sequentially:

When a user requests for a certain amount to be transferred into her bank account:

check whether any transaction can happen now? (transaction can be carried out only during a certain time period)

check whether the user has requested for a minimum amount to be withdrawn

check whether the user has any default account

The result of all the above actions should be logged.

If all the above condition satisfies, the transaction is carried out. In future, there might be some additional checks.

Which object oriented design pattern should be best suitable for the above case?


问:
Is there any alternative to function pointers in c++?
I am a novice c++ programmer who kept an idea that function pointers are a thing of C and OOP in C++ does not recommend its usage.

I know what I write here is vague/broad. But it will be great if somebody could comment whether my idea is completely wrong or something sensible.

Thanks.

答:
I don't think there is any widely accepted advice to avoid function pointers however there are some alternatives.

Virtual methods
One of the most common uses of function pointers in C is to implement dynamic dispatch. In C++ however this can be done for you (for single dispatch) by using virtual functions, indeed the usual implementation is that the compiler creates essentially a table of function pointers.

Functors

in the C++ sense, a functor is a small utility class that overloads operator() to behave like a first class function, as it's a normal class you can pass its objects around like any other objects without need for function pointers.

Lambdas

essentially provide a more convenient way to declare functors inline.

Templates

Provide a generic way to use/consume function pointers, functors or lambdas. So you can write higher order functions without needing function pointers, either by using a std::function parameter or directly using a template parameter.


问:
Is it okay to call functions when event occurs, or after that?
So I was not sure how to structure this title, feel free to edit it.

My question is:
When I have a Game Loop, I have 3 main blocks. Handle Events, Update game state, and draw.
Let's say for example I check for keyboard/mouse events, and I want to move my character when buttons are pressed.
Whenever KEYDOWN event occurs, should I immediately call Player.move?
Or should I toggle move_left/move_right bools, and then call Player.move when I'm in the Update game state block.

I was wondering this becouse, for example a function performs a long algorithm and I call it when an event occur's, calling the function will take some time, and meanwhile I might press more button's/events. I think I will lose some of those events becouse in that time the algirthm function was runing.

Or, I can toggle a bool when the event occurs, and after checking for ALL events, I perform functions based on the bools.

PS: Feel free to edit this post in a more constructive question.

答:
Well, simply put:

if you go with the "toggle booleans" way you risk "losing" user inputs. The user will sometimes click 3 times in order for his click to be "acknowledged" by such an input handling mechanism. For something like a fighting games which supports combos and such the effect would be very pronounced.

if you do something where the input event handler alters your game state directly (ignoring the game loop) is bad for several reasons: your code will no longer be nicely separated; even though technically there's no user input event that is skipped it mays STILL look like that to the human player as some input state changes can happen so fast the graphics rendering doesn't take them into account (imagine a red-blue, fast-blinking light, which changes color when the player pushes a button)

using an input queue is probablly the best way to go. Something like:

```<code>function processInput() {
   while(!inputEventsQueue.isEmpty()) {
        //you may decide to cap the maximum number of events delt with in one step
        InputEvent e = inputEventsQueue.pop();
        for(Entity e:gameEntities) {
            e.processInput(e)
        }
   }
}
</code>```

//game loop

while(...) {
  processInput();
  updateState();
  updateGraphics();
}

Body:
Well, simply put:

if you go with the "toggle booleans" way you risk "losing" user inputs. The user will sometimes click 3 times in order for his click to be "acknowledged" by such an input handling mechanism. For something like a fighting games which supports combos and such the effect would be very pronounced.

if you do something where the input event handler alters your game state directly (ignoring the game loop) is bad for several reasons: your code will no longer be nicely separated; even though technically there's no user input event that is skipped it mays STILL look like that to the human player as some input state changes can happen so fast the graphics rendering doesn't take them into account (imagine a red-blue, fast-blinking light, which changes color when the player pushes a button)

using an input queue is probablly the best way to go. Something like:

function processInput() {
   while(!inputEventsQueue.isEmpty()) {
        //you may decide to cap the maximum number of events delt with in one step
        InputEvent e = inputEventsQueue.pop();
        for(Entity e:gameEntities) {
            e.processInput(e)
        }
   }
}

//game loop

while(...) {
  processInput();
  updateState();
  updateGraphics();
}


问:
Does functional programming ignore the benefits gained from the "On the Criteria To Be Used in Decomposing Systems into Modules" (data hiding)?
There's a classic article named On the Criteria To Be Used in Decomposing Systems into Modules that I just read for the first time.  It makes perfect sense to me, and is probably one of those articles that OOP was based on.  Its conclusion:

We have tried to demonstrate by these examples that
  it is almost always incorrect to begin the decomposition
  of a system into modules on the basis of a flowchart.
  ... Each module is then designed to hide
  such a decision from the others

In my uneducated and inexperienced opinion, functional programming takes the exact opposite advice of this article.  My understanding is functional programming makes data flow idiomatic.  Data gets passed from function to function, each function being intimately aware of the data and "changing it" along the way.  And I think I've seen a Rich Hickey talk where he talks about how data hiding is overrated or unnecessary or something, but I can't remember for sure.

First I want to know if my assessment is correct.  Does the FP paradigm and this article philosophically disagree?

Assuming they disagree, how does FP "compensate" for its lack of data hiding?  Perhaps they sacrifice data hiding but gain X, Y and Z.  I'd like to know the reasoning for why X, Y and Z are considered more beneficial than data hiding.

Or, assuming they disagree, perhaps FP feels that data hiding is bad.  If so, why does it think data hiding is bad?

Assuming they agree, I'd like to know what FPs implementation of data hiding is.  It's obvious to see this in OOP.  You can have a private field that nobody outside the class can access.  There's no obvious analogy of this to me in FP.

I feel there are other questions I should be asking but I don't know I should be asking.  Feel free to answer those, too.

Update

I found this Neal Ford talk that has a very relevant slide in it.  I'll embed the screenshot here:

答:
Your belief that functional programming lacks data hiding is wrong. It just takes a different approach to hiding data. One of the most common ways of hiding data in functional programming is through the use of polymorphic functions that take a function as an argument. For example, this function

```<code>map :: (a -> b) -> [a] -> [b]
map _ [] = []
map f (x:xs) = f x : map f xs
</code>```

can only see the outermost structure of the data (i.e. that it is a list) it can't see anything about the data that the list contains and can only operate on the data through the single function that is passed to it.

The function that is passed as an argument is analogous to a public method on the data type that the list contains. It provides a limited way of operating on the data, but does not expose the internal workings of the data type.

Body:
Your belief that functional programming lacks data hiding is wrong. It just takes a different approach to hiding data. One of the most common ways of hiding data in functional programming is through the use of polymorphic functions that take a function as an argument. For example, this function

map :: (a -> b) -> [a] -> [b]
map _ [] = []
map f (x:xs) = f x : map f xs

can only see the outermost structure of the data (i.e. that it is a list) it can't see anything about the data that the list contains and can only operate on the data through the single function that is passed to it.

The function that is passed as an argument is analogous to a public method on the data type that the list contains. It provides a limited way of operating on the data, but does not expose the internal workings of the data type.


问:
ORM: Design of the service layer
I'm currently writing a medium sized web-application and find myself asking this question many times.

For example, let's say there are users, which have files (one-to-many). How should the UI access the data? One "extreme" would be to let the service layer "only" take care of the lazy loading, i.e.

```<code>public interface UserService {
    public User createUser(String loginName, String password);
    public Set<MediaFile> getFilesOfUser(User user);
}
</code>```

or, on the other hand, never return entities, only their ids

```<code>public interface UserService {
    public long createUser(String loginName, String password);
    public Set<Long> getFilesOfUser(long userId);
}
</code>```

This implies the service would need methods for querying (and setting) all "basic" attributes, too

```<code>public interface UserService {
    public long createUser(String loginName, String password);
    public Set<Long> getFilesOfUser(long userId);
    public String getNameOfUser(long userId);
    public void setNameOfUser(long userId, String name);
}
</code>```

This adds quite a bit of code (and possibly additional load to the DB), but also protects from StaleData- or LazyInitializationException.

Subquestion: How - if using the first case - should updating, fetching etc. be implemented? Two methods come to mind

First, I could try to manually update the original reference (because things like collection proxies, version etc. only get updated on the returned object, not the original reference). This simplifies using those entities directly in the UI

```<code>public Set<MediaFile> getFilesOfUser(User user) {
    Set<MediaFile> files = user.getFiles();
    if(!Hibernate.isInitialized(files)) {
        user.setFiles(userDao.findOne(user.getId()).getFiles()); // findOne to re-attach to the session
    return ImmutableSet.<MediaFile> copyOf(files);
}
</code>```

but also

```<code>public Set<MediaFile> getFilesOfUser(User user) {
    return ImmutableSet.<MediaFile> copyOf(getUser(user.getId()).getFiles());
}
</code>```

The major difference in those comes to show when using versioning. In the former case, I have to update version etc. manually (user.setVersion(attachedUser.getVersion())) after every update, in the latter, a update call has to re-fetch the entity every time just to set the value:

```<code>public void update(User user) {
    User attachedUser = getUser(user.getId());
    attachedUser.setName(user.getName());
    attachedUser.setPasswordHash(user.getPasswordHash());
    // etc etc
    userDao.save(attachedUser);
}
</code>```

This does not seem very efficient / unintuitive.

Which is the correct way to go?

EDIT

Just had an other idea related to the "only return id's" method: Services could expose a public "get___ById(long id)" method, which then can be used to at least read the basic values of the entity.

Additionally, one could implement "get___ByIdEagerly(long id)" and return a initialized entity, but I think that's a bad idea.

答:
So, I changed most of my code to the "only use the id"-approach. While re-writing I realized what my fallacy was: I interpreted references to entities as a representation of the object graph, whereas (I think) these just represent a snapshot of (a subset of) the current graph, with no guarantees to be updated. Designing the "UI-Level"-code around this resolves most of my issues with little to no work:

All events, constructors, etc. just pass the ids of the entities they are refering to. Also the service layer methods only take id's as arguments. If an instance needs information of an entity, it fetches it on demand and discards the entity object as soon as possible, meaning those references are never held outside the scope of a method (Exceptions can be made if you are sure that the values you are reading never get changed - but then, why would you read them again, anyways). This also implies: The service layer returns entities after a modification, but those objects also should never be saved longer than needed.

Example:

public MediaFile addFileToUser(long userId, File file, FileMetaData fileMetadata);
public User createUser(String loginName, String password, String fullName, String company);
public Set<MediaFile> getFilesOfUser(long userId);
```

I'm not sure if this is the recommended approach, but from my point of view it seems ok. No idea about the performance impact though (I don't know how hibernate caching works, but it seems logical to assume cacheing by id, so maybe this approach even is kinda fast)

Title: ORM: Design of the service layer

Body:
So, I changed most of my code to the "only use the id"-approach. While re-writing I realized what my fallacy was: I interpreted references to entities as a representation of the object graph, whereas (I think) these just represent a snapshot of (a subset of) the current graph, with no guarantees to be updated. Designing the "UI-Level"-code around this resolves most of my issues with little to no work:

All events, constructors, etc. just pass the ids of the entities they are refering to. Also the service layer methods only take id's as arguments. If an instance needs information of an entity, it fetches it on demand and discards the entity object as soon as possible, meaning those references are never held outside the scope of a method (Exceptions can be made if you are sure that the values you are reading never get changed - but then, why would you read them again, anyways). This also implies: The service layer returns entities after a modification, but those objects also should never be saved longer than needed.

Example:

public MediaFile addFileToUser(long userId, File file, FileMetaData fileMetadata);
public User createUser(String loginName, String password, String fullName, String company);
public Set<MediaFile> getFilesOfUser(long userId);

I'm not sure if this is the recommended approach, but from my point of view it seems ok. No idea about the performance impact though (I don't know how hibernate caching works, but it seems logical to assume cacheing by id, so maybe this approach even is kinda fast)


答:
It depends on the type of game you are making.

For an FPS you want to respond to what the user is doing right this second.  In such a case yes I would process all events and determine what the user is doing right now. Then do that in the update function.

For an RTS the meaning of current input depends on previous input. Skipping to only track the last action would royally screw stuff up. i.e. Select unit 1, attack unit 3, select unit 2, attack unit 4, drop the select unit 2 because it wasn't the last action on the event queue, now unit 1 is attacking unit 4, unit 2 isn't doing anything, unit 3 is still alive and not engaged.

For your game what would dropping input mean?  It could mean your game stays responsive even if the frame rate stutters. It could mean you screw up input state because one event depends on an earlier event in the stream.

Title: Is it okay to call functions when event occurs, or after that?

Body:
So I was not sure how to structure this title, feel free to edit it.

My question is:
When I have a Game Loop, I have 3 main blocks. Handle Events, Update game state, and draw.
Let's say for example I check for keyboard/mouse events, and I want to move my character when buttons are pressed.
Whenever KEYDOWN event occurs, should I immediately call Player.move?
Or should I toggle move_left/move_right bools, and then call Player.move when I'm in the Update game state block.

I was wondering this becouse, for example a function performs a long algorithm and I call it when an event occur's, calling the function will take some time, and meanwhile I might press more button's/events. I think I will lose some of those events becouse in that time the algirthm function was runing.

Or, I can toggle a bool when the event occurs, and after checking for ALL events, I perform functions based on the bools.

PS: Feel free to edit this post in a more constructive question.


答:
I understand your question as "A good/accepted way to test a class that depends on file system operations". I donot assume that you want to test the filesystem of your os.

In order to keep the effort to 'interfaces to your filesystem operations and "mock them out"' as @Doc Brown answer suggested as small as possible it is a good idea to use java binary streams or text reader (or ther equivalent in c# or the programming language you are using) instead of using Files with filenames directly in you tdd-developed class.

Example:

Using java I have implemented a class CsvReader

```<code>public class CsvReader {
    private Reader reader;

    public CsvReader(Reader reader) {
        this.reader = reader;
    }
}
</code>```

For testing I used in memory data like this

```<code>String contentOfCsv = "TestColumn1;TestColumn2\n"+
    "value1;value2\n";

CsvReader sut = new CsvReader(java.io.StringReader(contentOfCsv));
</code>```

or embend testdata into the resources

```<code>CsvReader sut = new CsvReader(getClass().getResourceAsStream("/data.csv"));
</code>```

In production I use the file system

```<code>CsvReader sut = new CsvReader(new BufferedReader( new FileReader( "/import/Prices.csv" ) ));
</code>```

This way my CsvReader does not depend on filesystem but on an abstraction "Reader" where there is an implementation for filesystem.

Body:
I understand your question as "A good/accepted way to test a class that depends on file system operations". I donot assume that you want to test the filesystem of your os.

In order to keep the effort to 'interfaces to your filesystem operations and "mock them out"' as @Doc Brown answer suggested as small as possible it is a good idea to use java binary streams or text reader (or ther equivalent in c# or the programming language you are using) instead of using Files with filenames directly in you tdd-developed class.

Example:

Using java I have implemented a class CsvReader

public class CsvReader {
    private Reader reader;

    public CsvReader(Reader reader) {
        this.reader = reader;
    }
}

For testing I used in memory data like this

String contentOfCsv = "TestColumn1;TestColumn2\n"+
    "value1;value2\n";

CsvReader sut = new CsvReader(java.io.StringReader(contentOfCsv));

or embend testdata into the resources

CsvReader sut = new CsvReader(getClass().getResourceAsStream("/data.csv"));

In production I use the file system

CsvReader sut = new CsvReader(new BufferedReader( new FileReader( "/import/Prices.csv" ) ));

This way my CsvReader does not depend on filesystem but on an abstraction "Reader" where there is an implementation for filesystem.


答:
I'm going to strike out on a limb here and say that the concept is just not relevant in FP the way it is in OO.

tl;dr;
The point of data hiding is to ensure responsibilities are maintained where they should be, and you don't have outside actors messing with data they don't have the knowledge for. In FP data is generated by expressions, and in this way you can't mess with the data because it's not mutable properties so much as composable computations which completely changes the rules of the game.

In my experiences with FP; which are admittedly insignificant, I tend to find one stark contrast with OO in what denotes good/common data modeling.

This contrast is that in OO in general you model things to represent your data. Obligatory car analogy:

OO

You have a car Object, that correctly hides details about the car such as the AC implementation (is it belt driven, or air-pressure-driven? Consumers shouldn't need to know, so hide it).

This car object has many properties and methods that delineate all the facts about the car as well as ways that you can work with a car.

This car object has properties which are components of a car that further hide from the overall Car their particular implementations, and their data facts allowing the components of the car to be interchangeable.

The thing to note here is when you're modeling things in an OO format, it's all about representing things as Data. You have objects with properties, many of those properties are objects with more properties. You have a couple methods here and there attached to those objects, but all they really do is usually jigger the properties of the objects this way and that, again it's very data-centric modeling; that is you model your data to be interacted with focussing on structuring it to make available all the points of your data so consumers may change the data this way and that.

FP

You have a great deal of computations that allow you to describe behaviours

These expressions of behaviour are related in a way that can be translated to the way a cars behaviours are related to eachother, such as a car having accelerate/decelerate, there are two behaviours which oppose eachother in a similar way.

The big difference between OO and FP that constantly strikes me is as I said above the way you model data. In OO as mentioned above you model data as data, in FP you model data as computations, expressions, algorithms, it's more about modeling the activities of your data than the facts of it. Think about basic data modeling in math, it's always about getting an equation that can generate your data, which models your data as the activity that causes it, as opposed to OO is modeling is coming up with a way to represent the data you have. That is much of the distinction between FP and OO.

Remember, for a great deal of time LISP, one of the foundational FP languages, lived with a very small amount of primitive data types. This works because the approach isn't about modeling complex representations of your data so much as computations that generate and express the behaviours of your system.

When I start writing some code in FP, I start by writing code that does something, where as when I start writing code in OO, I start by writing models that describe something. The doing of things is hidden in FP by being expressions, the doing of things is exposed in OO by being described with data, hiding this data limits said exposure.

Back to the question at hand, what does FP say about data hiding, does it appreciate it or disagree with it or what not?

I say it doesn't matter, in OO your data is the guts and important pieces in your program that should be hidden from being meddled with. In FP the guts and knowledge of your system is all hidden away in the algorithms and computations that express the system. These are by definition more or less immutable, the only way to mutate computation expressions are things like macros, but even then you're mutations definitions are expressions themselves which cannot be further meddled with.

Title: Does functional programming ignore the benefits gained from the "On the Criteria To Be Used in Decomposing Systems into Modules" (data hiding)?

Body:
There's a classic article named On the Criteria To Be Used in Decomposing Systems into Modules that I just read for the first time.  It makes perfect sense to me, and is probably one of those articles that OOP was based on.  Its conclusion:

We have tried to demonstrate by these examples that
  it is almost always incorrect to begin the decomposition
  of a system into modules on the basis of a flowchart.
  ... Each module is then designed to hide
  such a decision from the others

In my uneducated and inexperienced opinion, functional programming takes the exact opposite advice of this article.  My understanding is functional programming makes data flow idiomatic.  Data gets passed from function to function, each function being intimately aware of the data and "changing it" along the way.  And I think I've seen a Rich Hickey talk where he talks about how data hiding is overrated or unnecessary or something, but I can't remember for sure.

First I want to know if my assessment is correct.  Does the FP paradigm and this article philosophically disagree?

Assuming they disagree, how does FP "compensate" for its lack of data hiding?  Perhaps they sacrifice data hiding but gain X, Y and Z.  I'd like to know the reasoning for why X, Y and Z are considered more beneficial than data hiding.

Or, assuming they disagree, perhaps FP feels that data hiding is bad.  If so, why does it think data hiding is bad?

Assuming they agree, I'd like to know what FPs implementation of data hiding is.  It's obvious to see this in OOP.  You can have a private field that nobody outside the class can access.  There's no obvious analogy of this to me in FP.

I feel there are other questions I should be asking but I don't know I should be asking.  Feel free to answer those, too.

Update

I found this Neal Ford talk that has a very relevant slide in it.  I'll embed the screenshot here:


问:
Animation in Swing
I have a project written using Swing, and I want to make it more smoothly (like JavaFX is) by adding animation to some components(JButton, JScrollPane, JSplitPane) using javax.swing.Timer.

UPD: That is not a game. I want to use the Timer for short animations like mouseHover events or dropdown, or scroll. But the problem is, a lot of Timer objects should be created.

Question: What action does it perform for JVM? I would start and stop a lot of Timers during app session.

答:
No. Run your app with something akin to a game loop and update your components periodically that way. With a timer, you're going to get unreliable and choppy animation. This topic is too big to cover in detail here, but that's the basic idea.

Implementing animation with Swing is fine, but just don't use a timer.

HTH

Title: Animation in Swing