问:
Is there an established pattern for associating a database entry with a Java class that executes on that data?
I have a behavior tree with different leaf nodes that execute tasks. When building out the tree relationship in the database I need an association between the leaf node entry and the Java class that will actually perform the task execution. I've seen some examples that store the canonical name of the Java task class with the leaf node data, and then instantiate the class at runtime using reflection. I'm not sure I like that approach, but I'm looking for all of the alternatives so I can make an informed decision.</p>

答:
You can use JPA with inheritance.

There are several variations ("patterns"):

all objects share the same table and there is a "discriminant" column/attribute (this is the closest to the one you explain). It is quick for queries, but you will have a column for each attribute of a subclass (if you have 20.000 instances, and only two instances of a subclass that defines attribute "x", you will have 20.000 rows where attribute 'x' is implemented as a null column. And it is more difficult to enforce that, when the instance is of the given subclass, the attribute may not be null (you would require a programmed constraint).

each subclass has a different subclass (good if subclasses have lots of different attributes, but implies joins when querying the DB).

one table is used for common attributes, there are tables for attributes specific to subclasses (this is a hybrid of the other two).

The advantage is that it is standard, and you forget about how to persist/retrieve the data, the JPA already does it for you.

The disavantage is that it is a full API and you should learn how it does manage relationships(including cascading and/or lazy loading), JPQL/Criteria, etc.


问:
Does functional programming increase the 'representational gap' between problems and solutions?
Since machine language (e.g., 0110101000110101) computer languages have generally evolved to higher forms of abstraction, generally making it easier to understand the code when it's applied to a problem. Assembler was an abstraction over machine code, C was an abstraction over assembler, etc.

Object-oriented design seems to be very good at allowing us to model a problem in terms of objects, e.g., the problem of a university course registration system can be modeled with a Course class, a Student class, etc. Then, when we write the solution in an OO language, we have similar classes which get responsibilities and that generally is helpful for design, especially for modularizing the code. If I give this problem to 10 independent teams who solve it with an OO method, generally the 10 solutions will have the classes relating to the problem in common. There can be lots of differences when you start to get into coupling and interactions of those classes, so there's no such thing as "zero representational gap."

My experience with Functional Programming is very limited (no real-world use, only Hello World type programs). I'm failing to see how such languages allow easily mapping FP solutions to problems (with a low representational gap) the way OO languages do.

I understand the advantages of FP with respect to concurrent programming. But am I missing something, or is FP not about reducing a representational gap (making solutions easier to understand)?

Another way to ask this: would the FP code of 10 different teams solving the same real-world problem have a lot in common?

From Wikipedia on Abstraction (computer science) (emphasis mine):

Functional programming languages commonly exhibit abstractions related to functions, such as lambda abstractions (making a term into a function of some variable), higher-order functions (parameters are functions), bracket abstraction (making a term into a function of a variable).

The representational gap could be potentially increased, because [some] real-world problems aren't modeled easily with such abstractions.

Another way I see decreasing representational gap is in tracing the solution elements back to the problem. The 0's and 1s in machine code is very hard to trace back, whereas the Student class is easy to trace back. Not all OO classes trace easily to the problem space, but many do.

Don't FP abstractions always need explaining to find out which part of the problem space they are solving (apart from math problems)? OK - I'm good on this part. After looking at many more examples, I see how FP abstractions are very clear for parts of the problem that are expressed in data processing.

The accepted answer to a related question Can UML be used to model a Functional program? -- says "Functional programmers don't have a lot of use for diagrams." I really don't care if it's UML, but it makes me wonder about FP abstractions being easy to understand/communicate, if there are no diagrams that are widely used (assuming this answer is correct). Again, my level of FP use/understanding is trivial, so I understand no need for diagrams on simple FP programs.

OO design has function/class/package-levels of abstraction, with encapsulation (access control, information hiding) at each, which makes managing complexity easier. These are elements that allow going from the problem to the solution and back easier.

Many answers speak of how analysis and design are done in FP in a way analogous to OO, but nobody cites anything high-level so far (paul cited some interesting stuff, but it's low-level). I did a lot of Googling yesterday and found some interesting discussion. The following is from Refactoring Functional Programs by Simon Thompson (2004) (emphasis mine)

In designing an object-oriented system, it is taken for granted that design will
  precede programming. Designs will be written using a system like UML
  which is supported in tools such as Eclipse. Beginning programmers may
  well learn a visual design approach using systems like BlueJ. Work on a
  similar methodology for functional programming is reported in FAD: Functional Analysis and Design, but little
  other work exists. There may be a number of reasons for this.

Existing functional programs are of a scale which does not require design.
  Many functional programs are small, but others, such as the Glasgow Haskell
  Compiler, are substantial.

Functional programs directly model the application domain, thus rendering
  design irrelevant. Whilst functional languages provide a variety of powerful
  abstractions, it is difficult to argue that these provide all and only the
  abstractions needed to model the real world.

Functional programs are built as an evolving series of prototypes.

In the PhD thesis cited above, the benefits of using Analysis and design methodologies (ADM) are outlined independent of paradigms. But an argument is made that ADMs should align with the implementation paradigm. That is, OOADM works best for OO programming and is not well applied to another paradigm such as FP. Here's a great quote that I think paraphrases what I call representational gap:

one can argue at length regarding which paradigm
  provides the best support for software development, but one achieves the most natural,
  efficient and effective development package when one remains within a single paradigm
  from problem description through to implementation and delivery.

Here are the set of diagrams proposed by FAD:

function dependency diagrams which present a function with those it uses in its
  implementation;

type dependency diagram which provides the same service for types;
  and,

module dependency diagrams which present views of the module architecture of the system.

There's a case study in section 5.1 of the FAD thesis, which is a system to automate the production of data relating to a football (soccer) league. The requirements are 100% functional, e.g., input football results, produce league tables, scoring tables, attendance tables, transfer players between teams, updating data after new results, etc. No mention of how FAD works to solve non-functional requirements is documented, apart from stating that "new functionality should be allowed at a minimal cost", something that is nearly impossible to test.

Sadly, apart from FAD, I don't see any modern references for modeling languages (visual) that are proposed for FP. UML is another paradigm, so we should forget that.

答:
When I took my Java class years ago, we were expected to show our solutions to the entire class, so I got to see how people think; how they solve problems logically.  I fully expected the solutions to cluster around three or four common solutions.  Instead, I watched as 30 students solved the problem in 30 completely different ways.

Naturally, as fledgling programmers gain experience, they will gain exposure to common software patterns, begin using those patterns on their code, and then their solutions may coalesce around a few optimal strategies.  These patterns form a technical language by which experienced developers can communicate.

The technical language that underpins functional programming is math.  Accordingly, the problems that are most suitable to solve using functional programming are essentially math problems.  By math, I'm not referring to the kind of math that you would see in business solutions, like addition and subtraction.  Rather, I'm talking about the kind of math that you might see on Math Overflow, or the kind of math you would see in Orbitz' search engine (it's written in Lisp).

This orientation has some important ramifications for functional programmers trying to solve real-world programming problems:

Functional programming is more declarative than imperative; it concerns itself primarily with telling the computer what to do, not how to do it.

Object-oriented programs are often built from the top-down.  A class design is created, and the details are filled in.  Functional programs are often built from the bottom-up, starting with small, detailed functions that are combined into higher-level functions.

Functional programming can have advantages for prototyping complex logic, constructing flexible programs that can change and evolve organically, and building software where the initial design is unclear.

Object-oriented programs can be more suitable for business domains because the classes, messages between objects, and the software patterns all provide a structure that maps to the business domain, captures its business intelligence and documents it.

Because all practical software produces side-effects (I/O), purely functional programming languages require a mechanism to produce those side-effects while remaining mathematically pure (monads).

Functional programs can be more readily proven, due to their mathematical nature.  Haskell's type system can find things at compile time that most OO languages cannot.

And so on.  As with many things in computing, object-oriented languages and functional languages have different tradeoffs.

Some modern OO languages have adopted some of the useful functional programming concepts, so that you can have the best of both worlds.  Linq, and the language features that were added to support it, is a good example of that.

ContentLicense: CC BY-SA 3.0


问:
Best practices for usage of "shall" and "must" when writing requirements
I sent out an email earlier reminding our developers that

the use of the word "shall" in your derived requirements should not follow over to your functional requirements. When writing functional requirements the word "must" is used to describe the function a derived requirement must do.

Derived = System Shall be requirement

Functional = System must do requirement*

It was sent back by one of our seniors that this was wrong and that "shall" should be used in every requirement.

Am I wrong here, and should "shall" be used in every requirement?  I haven't been able to find anything to back that up.

答:
If you happen to work within the framework of DO-178 or DO-254 guidelines, these have their own definitions for requirements in general and derived requirements. These guidelines do not, however, specify which word, e.g. shall, should, must, should be used for specifying the requirements.

If your requirements management tooling does not automatically point out derived requirements for you, making these distinct from functional requirements by the use of a must instead of shall  can be beneficial, for example to demonstrate that the verification objectives for derived requirements have also been met. This could be a possible reason for the seemingly arbitrary documentation requirement.

Note that in DO-178 and DO-254 derived requirement actually means a requirement which has not been derived from a higher-level requirement. A derived requirements therefore essentially initiates a new chain of traceability.

Both the DO-178 and the DO-254 are commercial guideline documents used for avionics software and electronics development, and only available for a fee from www.rtca.org.

OwnerDisplayName: Tim Lieberman

ContentLicense: CC BY-SA 4.0


问:
What was your most difficult bug hunt and how did you find it and kill it?
This is a "Share the Knowledge" question. I am interested in learning from your successes and/or failures.

Information that might be helpful...

Background:

Context: Language, Application,
Environment, etc.

How was the bug identified ?

Who or what identified the bug ?

How complex was reproducing the bug ?

The Hunting.

What was your plan  ?

What difficulties did you encounter ?

How was the offending code finally found ?

The Killing.

How complex was the fix ?

How did you determine the scope of the fix ?

How much code was involved in the fix ?

Postmortem.

What was the root cause technically ? buffer overrun, etc.

What was the root cause from 30,000 ft ?

How long did the process ultimately take ?

Were there any features adversely effected by the fix ?

What methods, tools, motivations did you find particularly helpful ? ...horribly useless ?

If you could do it all again
?............

These examples are general, not applicable in every situation and possibly useless. Please season as needed.

答:
It was actually in a 3rd party image viewer sub-component of our application.

We found that there were 2-3 of the users of our application would frequently have the image viewer component throw an exception and die horribly. However, we had dozens of other users who never saw the issue despite using the application for the same task for most of the work day. Also there was one user in particular who got it a lot more frequently than the rest of them.

We tried the usual steps:

(1) Had them switch computers with another user who never had the problem to rule out the computer/configuration. - The problem followed them.

(2) Had them log into the application and work as a user that never saw the problem. - The problem STILL followed them.

(3) Had the user report which image they were viewing and set up a test harness to repeat viewing that image thousands of times in quick succession. The problem did not present itself in the harness.

(4) Had a developer sit with the users and watch them all day. They saw the errors, but didn't notice them doing anything out of the ordinary to cause them.

We struggled with this for weeks trying to figure out what the "Error Users" had in common that the other users didn't. I have no idea how, but the developer in step (4) had a eureka moment on the drive in to work one day worthy of Encyclopedia Brown.

He realized that all the "Error Users" were left handed, and confirmed this fact. Only left-handed users got the errors, never Righties. But how could being left handed cause a bug?

We had him sit down and watch the left-handers again specifically paying attention to anything they might be doing differently, and that's how we found it.

It turned out that the bug only happened if you moved the mouse to rightmost column of pixels in the image viewer while it was loading a new image (overflow error because the vendor had a 1-off calculation for mouseover event).

Apparently, while waiting for the next image to load, the users all naturally moved their hand (and thus the mouse)  towards the keyboard.

The one user who happened to get the error most frequently was one of those ADD types that compulsively moved her mouse around a lot impatiently while waiting for the next page to load, thus she was moving the mouse to the right much more quickly and hitting the timing just right so she did it when the load event happened. Until we got a fix from the vendor, we told her just to let go of the mouse after clicking (next document) and not touch it until it loaded.

It was henceforth known in legend on the dev team as "The Left Handed Bug"

ContentLicense: CC BY-SA 2.5


问:
If you take a year or two out from being a developer, is it really that hard to get back into it?
I've been working as a developer for about 3 years now (straight from uni), I'm wondering, if I take a year or two out would it be impossible to get back into the industry?

I didn't get the gap year thing out of my system after uni, and I'm thinking that I should probably do it before I hit 30 (24 now), my main concern is that if I leave the industry now, I might not get back into it at all and end up working some dead end job.

The way I see things is, that general concepts / design patterns etc remain similar over the years, and it is mostly coding syntax / actual implementation that evolves, so it shouldn't move on dramatically.

Also, women developers (yes there are some out there!) take years out to have kids and still carry on with their career afterwards, so it can't be impossible.

Ultimatum : Would taking a year or two out destroy the (small) career I've built up so far?

答: Given that programmers need to learn new techs every X years, taking a year off does not necessarily put your career in pitfall when compared with a guy who has the pressure of everyday work with existing codebase PLUS having to learn new techs. This is all however very individual I guess.</p>


问:
Is a software licence required?
I'm a developer of open source applications and publish my applications and smaller source code snippets on my personal website. I also often find and use code by others, often from blogs or small websites that just display a few lines of clever code, or offer a few source files for download. Most of the time, no licence is attached to these snippets and downloads.

So my question is, when I'm publishing such snippets or modules, do I need to declare a licence for them? If I do, it would probably be the 2-clause BSD or the MIT licence or something similar.

I've found an article about making those shorter and wondered whether such a licence is any good at all. Copyright always applies if declared. There's no need to require to accept that. Liability should never apply, I guess, but I have no idea about that. I mean, if I publish any piece of information on the web, or anywhere, and somebody uses it and that causes damage to them, can I be liable for that?

I like the idea of a very short authorship and permissions declaration like the following:

Copyright 2015, My Name, http://my.website

  Redistribution and use in source and binary forms, with or without modification, are permitted.

Would that work?

答:
It's always better to have some sort of license, even if it's as simple as your example.

Code without a license cannot be assumed to be in the public domain.  The author of the code always has an implicit copyright, at least in the United States, and if the author hasn't stated any permissions... well, then you don't have permission.

Even if the author has explicitly put their code in the public domain, the notion of "public domain" is a gray area in some countries.

Title: Is a software licence required?


答:
It is not a great idea to write a license by yourself. Even if its wordings would be absolutely correct, people might be in doubt about it validity.

The shortest free software license I met, that is considered valid by some authoritative organization is GNU All-Permissive License:

```<code>Copyright <year> <name>

Copying and distribution of this file, with or without modification,
are permitted in any medium without royalty provided the copyright
notice and this notice are preserved.  This file is offered as-is,
without any warranty.
</code>```

You might consider using it.

Title: Is a software licence required?

Body:
I'm a developer of open source applications and publish my applications and smaller source code snippets on my personal website. I also often find and use code by others, often from blogs or small websites that just display a few lines of clever code, or offer a few source files for download. Most of the time, no licence is attached to these snippets and downloads.

So my question is, when I'm publishing such snippets or modules, do I need to declare a licence for them? If I do, it would probably be the 2-clause BSD or the MIT licence or something similar.

I've found an article about making those shorter and wondered whether such a licence is any good at all. Copyright always applies if declared. There's no need to require to accept that. Liability should never apply, I guess, but I have no idea about that. I mean, if I publish any piece of information on the web, or anywhere, and somebody uses it and that causes damage to them, can I be liable for that?

I like the idea of a very short authorship and permissions declaration like the following:

Copyright 2015, My Name, http://my.website

  Redistribution and use in source and binary forms, with or without modification, are permitted.

Would that work?

Body:
It is not a great idea to write a license by yourself. Even if its wordings would be absolutely correct, people might be in doubt about it validity.

The shortest free software license I met, that is considered valid by some authoritative organization is GNU All-Permissive License:

Copyright <year> <name>

Copying and distribution of this file, with or without modification,
are permitted in any medium without royalty provided the copyright
notice and this notice are preserved.  This file is offered as-is,
without any warranty.

You might consider using it.


问:
Throw exception or let code fail
I am wondering if there are any pros and cons against this style:

```<code>private void LoadMaterial(string name)
{
    if (_Materials.ContainsKey(name))
    {
        throw new ArgumentException("The material named " + name + " has already been loaded.");
    }

    _Materials.Add(
        name,
        Resources.Load(string.Format("Materials/{0}", name)) as Material
    );
}
</code>```

That method should, for each name, be run only once. _Materials.Add() will throw an exception if it will be called multiple times for the same name. Is my guard, as a result, completely redundant, or there are some less obvious benefits?

That's C#, Unity, if anyone is interested.

答:
There are already a few answers here, but here's answer that takes Unity3D into account (the answer is very specific to Unity3D, I'd do most of this very differently in most contexts):

In general, Unity3D doesn't use exceptions traditionally. If you throw an exception in Unity3D, it's nothing like in your average .NET application, namely it won't stop the program, t most you can configure the editor to pause. It'll just get logged. This can easily put the game in an invalid state and create a cascade effect that makes errors difficult to track down. So I'd say in the case of Unity, letting Add throw an exception is an especially undesirable option.

But on the examining the speed of exceptions isn't a case of premature optimization in some cases because of how Mono works in Unity on some platforms. In fact, Unity3D on iOS supports some advanced script optimizations, and disabled exceptions* is a side effect of one of them. This is really something to consider because those optimizations haven proven very valuable for many users, showing a realistic case for considering limiting the use of exceptions in Unity3D. (*managed exceptions from the engine, not your code)

I'd say that in Unity you might want to take a more specialized approach. Ironically, a very down-voted answer at the time of writing this, shows one way I might implement something like this specifically in the context of Unity3D (elsewhere something like this really is unacceptable, and even in Unity it's fairly inelegant).

Another approach I'd consider is actually not indicating an error far as the caller is concerned, but rather using the Debug.LogXX functions. That way you get the same behavior as throwing an unhandled exception (because of how Unity3D handles them) without risking putting something in an strange state down the line. Also consider if this really is an error (Is trying to load the same material twice necessarily an error in your case? Or might this be a case where Debug.LogWarning is more applicable).

And in regards to the using things like Debug.LogXX functions instead of exceptions, you still have to consider what happens when an exception would be thrown from something that returns a value (like GetMaterial). I tend to approach this by passing null along with logging the error (again, only in Unity). I then use null checks in my MonoBehaviors to ensure any dependency like a material is not a null value, and disable the MonoBehavior if it is. An example for a simple behavior that requires a few dependencies is something like this:

```<code>    public void Awake()
    {
        _inputParameters = GetComponent<VehicleInputParameters>();
        _rigidbody = GetComponent<Rigidbody>();
        _rigidbodyTransform = _rigidbody.transform;
        _raycastStrategySelector = GetComponent<RaycastStrategySelectionBehavior>();

        _trackParameters =
            SceneManager.InstanceOf.CurrentSceneData.GetValue<TrackParameters>();

        this.DisableIfNull(() => _rigidbody);
        this.DisableIfNull(() => _raycastStrategySelector);
        this.DisableIfNull(() => _inputParameters);
        this.DisableIfNull(() => _trackParameters);
    }
</code>```

SceneData.GetValue<> is similar to your example in that it calls a function on a dictionary that throws an exception. But instead of throwing an exception it uses Debug.LogError which gives a stack trace like a normal exception would and returns null. The checks that follow* will disable the behavior instead of letting it continue to exist in an invalid state.

*the checks look like that because of a small helper I use that prints out a formatted message when it disables the game object**. Simple null checks with if work here (** the helper's checks are only compiled in Debug builds (like asserts). Using lambdas and expressions like that in Unity can take it's toll on performance)

Title: Throw exception or let code fail

Body:
There are already a few answers here, but here's answer that takes Unity3D into account (the answer is very specific to Unity3D, I'd do most of this very differently in most contexts):

In general, Unity3D doesn't use exceptions traditionally. If you throw an exception in Unity3D, it's nothing like in your average .NET application, namely it won't stop the program, t most you can configure the editor to pause. It'll just get logged. This can easily put the game in an invalid state and create a cascade effect that makes errors difficult to track down. So I'd say in the case of Unity, letting Add throw an exception is an especially undesirable option.

But on the examining the speed of exceptions isn't a case of premature optimization in some cases because of how Mono works in Unity on some platforms. In fact, Unity3D on iOS supports some advanced script optimizations, and disabled exceptions* is a side effect of one of them. This is really something to consider because those optimizations haven proven very valuable for many users, showing a realistic case for considering limiting the use of exceptions in Unity3D. (*managed exceptions from the engine, not your code)

I'd say that in Unity you might want to take a more specialized approach. Ironically, a very down-voted answer at the time of writing this, shows one way I might implement something like this specifically in the context of Unity3D (elsewhere something like this really is unacceptable, and even in Unity it's fairly inelegant).

Another approach I'd consider is actually not indicating an error far as the caller is concerned, but rather using the Debug.LogXX functions. That way you get the same behavior as throwing an unhandled exception (because of how Unity3D handles them) without risking putting something in an strange state down the line. Also consider if this really is an error (Is trying to load the same material twice necessarily an error in your case? Or might this be a case where Debug.LogWarning is more applicable).

And in regards to the using things like Debug.LogXX functions instead of exceptions, you still have to consider what happens when an exception would be thrown from something that returns a value (like GetMaterial). I tend to approach this by passing null along with logging the error (again, only in Unity). I then use null checks in my MonoBehaviors to ensure any dependency like a material is not a null value, and disable the MonoBehavior if it is. An example for a simple behavior that requires a few dependencies is something like this:

    public void Awake()
    {
        _inputParameters = GetComponent<VehicleInputParameters>();
        _rigidbody = GetComponent<Rigidbody>();
        _rigidbodyTransform = _rigidbody.transform;
        _raycastStrategySelector = GetComponent<RaycastStrategySelectionBehavior>();

        _trackParameters =
            SceneManager.InstanceOf.CurrentSceneData.GetValue<TrackParameters>();

        this.DisableIfNull(() => _rigidbody);
        this.DisableIfNull(() => _raycastStrategySelector);
        this.DisableIfNull(() => _inputParameters);
        this.DisableIfNull(() => _trackParameters);
    }

SceneData.GetValue<> is similar to your example in that it calls a function on a dictionary that throws an exception. But instead of throwing an exception it uses Debug.LogError which gives a stack trace like a normal exception would and returns null. The checks that follow* will disable the behavior instead of letting it continue to exist in an invalid state.

*the checks look like that because of a small helper I use that prints out a formatted message when it disables the game object**. Simple null checks with if work here (** the helper's checks are only compiled in Debug builds (like asserts). Using lambdas and expressions like that in Unity can take it's toll on performance)


答:
I think this is more a question about API design than a coding convention question.

What is the expected result (the contract) of calling:

```<code>LoadMaterial("wood");
</code>```

If the caller may expect / is guaranteed that after calling this method, the material "wood" is loaded, then i don't see any reason to throw an exception when that material is already loaded.

If an error occurs when loading the material, for example, the database connection could not be opened, or there is no material "wood" in the repository, then it is correct to throw an exception to notify the caller of that problem.

Title: Throw exception or let code fail

Body:
I am wondering if there are any pros and cons against this style:

```<code>private void LoadMaterial(string name)
{
    if (_Materials.ContainsKey(name))
    {
        throw new ArgumentException("The material named " + name + " has already been loaded.");
    }

    _Materials.Add(
        name,
        Resources.Load(string.Format("Materials/{0}", name)) as Material
    );
}
</code>```

That method should, for each name, be run only once. _Materials.Add() will throw an exception if it will be called multiple times for the same name. Is my guard, as a result, completely redundant, or there are some less obvious benefits?

That's C#, Unity, if anyone is interested.

Body:
I think this is more a question about API design than a coding convention question.

What is the expected result (the contract) of calling:

LoadMaterial("wood");

If the caller may expect / is guaranteed that after calling this method, the material "wood" is loaded, then i don't see any reason to throw an exception when that material is already loaded.

If an error occurs when loading the material, for example, the database connection could not be opened, or there is no material "wood" in the repository, then it is correct to throw an exception to notify the caller of that problem.


问:
Using many Resource URI to create a Record and handling failure
Hi Guys,

I have a decision to make to solve a problem, I’m describing the problem below.

Application Overview

I have an ASP.NET MVC 4 webApp which uses Rest Api for almost all the tasks, from Login to CRUD on the records.

The rest api is being developed by a separate disjoint team and the webApp is being developed my me.

There is a particular scenario which leads me to think that something is not right may be the Api is having an issue or I’m not developing the WebApp the right way.

I made a screen for Employee creation, it collects several information related to an employee, on submit to the server I collect these information serialize them into json and send them to Resource URI using the POST method.

The problem is in order to create a single employee I would need to hit four Resource URI one by one,the Person needs to be created first (its the independent record) and then I can proceed with the person_id to create Phone,Email and Address.

Person > (Phone | Email | Address)

Possible Issues:

Now If the Person creation fails I would show user that the operation failed and he/she could try again.
If the person creation succeeds but one or more preceding record creation fails then actually Employee creation fails,it's kind of a transaction all record should be created to successfully create employee.
Also a useless person will be hanging around of no worth and then the Application user might try to create the employee again and this problem may happen again.

Possible Solutions

A) Solution at my End:
Make a windows service running with a scheduler,which checks a DB if failed requests are there,and if it finds any it performs the api request to complete the tasks.

B) API Level Solution:
Make an Employee Resource URI which is able to receive the json of all the distinct json objects in a single go and respond with result.
Of course these separate json object may correspond to separate DB tables and the API developer will handle them through transaction.

C) Use QueueBackgroundWorkItem
use the QBWI to quickly make several async request for the failed resources and return with failed and success message also log and email the admin,no need to manage a separate Windows Service and a DB.

for more details on QBWI.

Remarks:
I will go for the solution B ,its seems like the best option but due to time constraint I might need to apply the solution (C)

Guys I need you to critically examine the scenario and the solution sections and provide me analysis and the best possible solution.

答:
B definitely sounds like the only sane choice.

A means depending on implementation details of the REST API. It makes the "transaction" very fragile, breaks encapsulation, and other bad things.

C I'm not entirely sure what you're saying you'll do with a QBWI (beyond the email to admin part), but it doesn't sound like an actual solution to the problem. Something as simple and fundamental as transaction semantics definitely needs to be handled by the software, not by human admins.

In the real world, the "disjoint team" may fail to deliver a real solution. This would be when you talk to business managers and explain to them that you can do a hacky workaround (A or C) in the short term but you really need the other team to give you a proper API someday. They're the ones in a position to decide whether it's better for the company to do the workaround now or have you do something else for the time being.


答:
The basic data is structured the same in pretty much any paradigm. You're going to have a Student, a Course, etc. whether it's an object, a struct, a record, or whatever.  The difference with OOP isn't how the data is structured, it's how the functions are structured.

I actually find functional programs much more closely match how I think about a problem. For example, to plan a student's schedule for next semester, you think about things like lists of courses a student has completed, courses in a student's degree program, courses offered this semester, courses a student has completed prerequisites for, courses with times that don't conflict, etc.

Suddenly, it's not so clear which class should create and store all these lists. Even less so when you have complex combinations of these lists.  However, you must choose one class.

In FP, you write functions that take a student and a list of courses and return a filtered list of courses. You can group all such functions together in a module. You don't have to couple it with one class or another.

So your data models end up looking more like how OOP programmers think of their models, before they get polluted with classes that have no other purpose than providing convenient places to put functions that operate on combinations of other classes. No weird CourseStudentFilterList or similar classes that you always end up needing in OOP, but never think about in the beginning design.

Title: Does functional programming increase the 'representational gap' between problems and solutions?

Body:
Since machine language (e.g., 0110101000110101) computer languages have generally evolved to higher forms of abstraction, generally making it easier to understand the code when it's applied to a problem. Assembler was an abstraction over machine code, C was an abstraction over assembler, etc.

Object-oriented design seems to be very good at allowing us to model a problem in terms of objects, e.g., the problem of a university course registration system can be modeled with a Course class, a Student class, etc. Then, when we write the solution in an OO language, we have similar classes which get responsibilities and that generally is helpful for design, especially for modularizing the code. If I give this problem to 10 independent teams who solve it with an OO method, generally the 10 solutions will have the classes relating to the problem in common. There can be lots of differences when you start to get into coupling and interactions of those classes, so there's no such thing as "zero representational gap."

My experience with Functional Programming is very limited (no real-world use, only Hello World type programs). I'm failing to see how such languages allow easily mapping FP solutions to problems (with a low representational gap) the way OO languages do.

I understand the advantages of FP with respect to concurrent programming. But am I missing something, or is FP not about reducing a representational gap (making solutions easier to understand)?

Another way to ask this: would the FP code of 10 different teams solving the same real-world problem have a lot in common?

From Wikipedia on Abstraction (computer science) (emphasis mine):

Functional programming languages commonly exhibit abstractions related to functions, such as lambda abstractions (making a term into a function of some variable), higher-order functions (parameters are functions), bracket abstraction (making a term into a function of a variable).

The representational gap could be potentially increased, because [some] real-world problems aren't modeled easily with such abstractions.

Another way I see decreasing representational gap is in tracing the solution elements back to the problem. The 0's and 1s in machine code is very hard to trace back, whereas the Student class is easy to trace back. Not all OO classes trace easily to the problem space, but many do.

Don't FP abstractions always need explaining to find out which part of the problem space they are solving (apart from math problems)? OK - I'm good on this part. After looking at many more examples, I see how FP abstractions are very clear for parts of the problem that are expressed in data processing.

The accepted answer to a related question Can UML be used to model a Functional program? -- says "Functional programmers don't have a lot of use for diagrams." I really don't care if it's UML, but it makes me wonder about FP abstractions being easy to understand/communicate, if there are no diagrams that are widely used (assuming this answer is correct). Again, my level of FP use/understanding is trivial, so I understand no need for diagrams on simple FP programs.

OO design has function/class/package-levels of abstraction, with encapsulation (access control, information hiding) at each, which makes managing complexity easier. These are elements that allow going from the problem to the solution and back easier.

Many answers speak of how analysis and design are done in FP in a way analogous to OO, but nobody cites anything high-level so far (paul cited some interesting stuff, but it's low-level). I did a lot of Googling yesterday and found some interesting discussion. The following is from Refactoring Functional Programs by Simon Thompson (2004) (emphasis mine)

In designing an object-oriented system, it is taken for granted that design will
  precede programming. Designs will be written using a system like UML
  which is supported in tools such as Eclipse. Beginning programmers may
  well learn a visual design approach using systems like BlueJ. Work on a
  similar methodology for functional programming is reported in FAD: Functional Analysis and Design, but little
  other work exists. There may be a number of reasons for this.

Existing functional programs are of a scale which does not require design.
  Many functional programs are small, but others, such as the Glasgow Haskell
  Compiler, are substantial.

Functional programs directly model the application domain, thus rendering
  design irrelevant. Whilst functional languages provide a variety of powerful
  abstractions, it is difficult to argue that these provide all and only the
  abstractions needed to model the real world.

Functional programs are built as an evolving series of prototypes.

In the PhD thesis cited above, the benefits of using Analysis and design methodologies (ADM) are outlined independent of paradigms. But an argument is made that ADMs should align with the implementation paradigm. That is, OOADM works best for OO programming and is not well applied to another paradigm such as FP. Here's a great quote that I think paraphrases what I call representational gap:

one can argue at length regarding which paradigm
  provides the best support for software development, but one achieves the most natural,
  efficient and effective development package when one remains within a single paradigm
  from problem description through to implementation and delivery.

Here are the set of diagrams proposed by FAD:

function dependency diagrams which present a function with those it uses in its
  implementation;

type dependency diagram which provides the same service for types;
  and,

module dependency diagrams which present views of the module architecture of the system.

There's a case study in section 5.1 of the FAD thesis, which is a system to automate the production of data relating to a football (soccer) league. The requirements are 100% functional, e.g., input football results, produce league tables, scoring tables, attendance tables, transfer players between teams, updating data after new results, etc. No mention of how FAD works to solve non-functional requirements is documented, apart from stating that "new functionality should be allowed at a minimal cost", something that is nearly impossible to test.

Sadly, apart from FAD, I don't see any modern references for modeling languages (visual) that are proposed for FP. UML is another paradigm, so we should forget that.


答:
I would like to stress an aspect that I find important and that has not been covered in the other answers.

First of all, I think that the representational gap between problems and solutions can be more in the mind of the programmer, according to their background and to the concepts they are more familiar with.

OOP and FP look at data and operations from two different perspectives and provide different tradeoffs, as Robert Harvey has pointed out already.

One important aspect in which they differ is the way in which they allow to extend your software.

Consider the situation in which you have a collection of data types and a collection of operations, for example you have different image formats and you maintain a library of algorithms to process images.

Functional programming makes it easier to add new operations to your software: you only need a local change in your code, namely you add a new function, which handles different input data formats. On the other hand, adding new formats is more involved: you need to change all the functions you have already implemented (non local change).

The object-oriented approach is symmetric to this: each data type carries its own implementation of all the operations and is responsible of choosing the right implementation at runtime (dynamic dispatching). This makes it easy to add a new data type (e.g. a new image format): you just add a new class and implement all its methods. On the other hand, adding a new operation means to change all the classes that need to provide that operation. In many languages this is done by extending an interface and adapting all classes implementing it.

This different approach to extension is one of the reasons why OOP is more appropriate for certain problems where the set of operations varies less often than the set of data types on which these operations work. A typical example are GUIs: you have a fixed set of operations that all widgets must implement (paint, resize, move, and so on) and a collection of widgets that you want to extend.

So, according to this dimension, OOP and FP are just two specular ways of organizing your code. See SICP, in particular Section 2.4.3, Table 2.22, and paragraph Message passing.

Summarizing: in OOP you use data to organize operations, in FP you use operations to organize data. Each approach is stronger or weaker according to the context. In general, none of the two has a higher representational gap between problem and solution.


问:
Repository pattern vs DAO managing Entities
I am new to concepts like DAO, DAL and Domain Driven Design. In the end I want to decouple the persistence layer (mysql database) from my business objects and logic in a web application. I liked the DAO concept but I got stuck implementing it when I want to create a Business Object from database that has other entities associated with it (represented by foreign key in the db table).

How are these references (aggregations) handled using DAO pattern? Every online DAO example is simple and shows creation of value-object-like Business Objects only (without referencing other entities or value objects). Is it done using Dependency Injection and if so, where is the dependency created?

By further reading I guess that Repository pattern from DDD gives the possibility to maybe use DAOs behind the scenes and handle object aggregations. As I understand it, it only provides the so called root (Entity with all references loaded or lazy loaded) to the outer world, what seems a good approach to me. Is Repository recommended when using DAO or can DAOs themselves give this functionality by maintaining Persistence Ignorance to the Business Objects.

I am not using an ORM tool and don't want to as I like to explore these basic patterns directly

答:
This is where ORM (object-relational mapping) comes in handy. There are libraries for many programming languages, that provide this type of programming techniques. E.g. for Java there is Hibernate. Hibernate works with Java annotations. Here's a simple example for a many to one relationship from the official documentation:</p>

```<code>@Entity
public class Flight implements Serializable {
    @ManyToOne(cascade={CascadeType.PERSIST, CascadeType.MERGE})
    @JoinColumn(name="COMP_ID")
    public Company getCompany() {
        return company;
    }
    ...
}
</code>```

Body:
This is where ORM (object-relational mapping) comes in handy. There are libraries for many programming languages, that provide this type of programming techniques. E.g. for Java there is Hibernate. Hibernate works with Java annotations. Here's a simple example for a many to one relationship from the official documentation:

@Entity
public class Flight implements Serializable {
    @ManyToOne(cascade={CascadeType.PERSIST, CascadeType.MERGE})
    @JoinColumn(name="COMP_ID")
    public Company getCompany() {
        return company;
    }
    ...
}


答:
there is problem in ur requirement gathering
1st u said "...(its the independent record) and then I can proceed with the person_id to create Phone,Email and Address"

then u said : If the person creation succeeds but one or more preceding record creation fails then actually Employee creation fails"

means it is not independent.

lets assume its independent
then it means user can add orr update its address resource, phone resource etc after words.

solution like u can redesign this screen in way that first u create user with Person Resource and then get his other informations afterwards.

and if its dependent then u cannot disjoint the resource like that, in API u have give complete information to perform task.
User creation is a task and its complete information is all together.

Title: Using many Resource URI to create a Record and handling failure

Body:
Hi Guys,

I have a decision to make to solve a problem, I’m describing the problem below.

Application Overview

I have an ASP.NET MVC 4 webApp which uses Rest Api for almost all the tasks, from Login to CRUD on the records.

The rest api is being developed by a separate disjoint team and the webApp is being developed my me.

There is a particular scenario which leads me to think that something is not right may be the Api is having an issue or I’m not developing the WebApp the right way.

I made a screen for Employee creation, it collects several information related to an employee, on submit to the server I collect these information serialize them into json and send them to Resource URI using the POST method.

The problem is in order to create a single employee I would need to hit four Resource URI one by one,the Person needs to be created first (its the independent record) and then I can proceed with the person_id to create Phone,Email and Address.

Person > (Phone | Email | Address)

Possible Issues:

Now If the Person creation fails I would show user that the operation failed and he/she could try again.
If the person creation succeeds but one or more preceding record creation fails then actually Employee creation fails,it's kind of a transaction all record should be created to successfully create employee.
Also a useless person will be hanging around of no worth and then the Application user might try to create the employee again and this problem may happen again.

Possible Solutions

A) Solution at my End:
Make a windows service running with a scheduler,which checks a DB if failed requests are there,and if it finds any it performs the api request to complete the tasks.

B) API Level Solution:
Make an Employee Resource URI which is able to receive the json of all the distinct json objects in a single go and respond with result.
Of course these separate json object may correspond to separate DB tables and the API developer will handle them through transaction.

C) Use QueueBackgroundWorkItem
use the QBWI to quickly make several async request for the failed resources and return with failed and success message also log and email the admin,no need to manage a separate Windows Service and a DB.

for more details on QBWI.

Remarks:
I will go for the solution B ,its seems like the best option but due to time constraint I might need to apply the solution (C)

Guys I need you to critically examine the scenario and the solution sections and provide me analysis and the best possible solution.


问:
Test driven development workflow for two programmers
We are currently starting with TDD and we want to work in parallel in two programmers - one for writing test (Programmer A) and one for writing actual code (Programmer B). Problem is, how to synchronize our work.

Let's say A writes first test method, so B can start working on actual code. Our current workflow is that A will do commit/push, and B will pull his changes. In time it's bit annoying, because after every change in test (new test method/bug in current test method/some other update) requires commit/push/pull and it interrupts both developers...

Is there some "best practices" for TDD? Some synchronization between their codes, mirroring, already existing tool etc? Thanks for any tip!

答:
In TDD, writing tests and code is interwoven, the cycles are typically very short, sometimes minutes, sometimes less. And TDD is a whitebox technique - when writing the next test, you know exactly what is missing in the current state of the implementation and you design the test exactly for this case.

So if you really want to try this with two developers, your best shot would probably be doing pair programming: sit both in front of the same screen (or use a screen sharing software), and do it together. That way, there will be no VCS involved, which solves any of your synchronization problems.


答:
As Niklaus Wirth put it, "Algorithms + Data Structures = Programs". Functional programming is about the way to organize algorithms, and it does not tell a lot about ways to organize data structures. Indeed, there exist FP languages both with mutable (Lisp) and immutable (Haskell, Erlang) variables. If you want to compare and contrast FP with something, you should pick imperative (C, Java) and declarative (Prolog) programming.

OOP is on the other hand a way to build data structures and attach algorithms to them. FP does not prevent you from building data structures similar to OOP ones. If you don't believe me, have a look at Haskell type declarations. However, most FP languages agree that functions do not belong to data structures and should rather be in the same namespace. This is done in order to simplify building new algorithms via function composition. Indeed, if you know what input a function takes and what output it produces, why should it matter which data structure it belongs too? For example, why does add function have to be called on an instance of Integer type and passed an argument instead of simply being passed two Integer arguments?

Therefore, I don't see why FP should make solutions harder to understand in general, and I don't think it does it anyway. However, keep in mind that a seasoned imperative programmer will certainly find functional programs harder to understand than imperative ones, and vice versa. This is similar to Windows - Linux dichotomy when folks who have invested 10 years in becoming comfortable with Windows environment find Linux difficult after a month of usage, and those who are used to Linux cannot achieve the same productivity in Windows. Hence, the 'representational gap' you are talking about is very subjective.


问:
Design Pattern to parse array of objects
What is considered a good practice to parse an array of objects returned by an API?

I am creating a RESTfull web service and a client which is meant to work with this service.

One of my REST services returns a JSON array in the following format:

```<code>{
  "objectsArray": [
    {
      "PropertyA": 10,
      "PropertyB": "A String",
      "PropertyC": true,
    },
    {
      "PropertyA": 20,
      "PropertyB": "Another String",
      "PropertyC": false,
    }
  ]
}
</code>```

In my client I would like to parse this JSON array and map it to the model, but I am not sure where to place the parsing logic to keep the loose coupling.

What I already have:

Model class. From the example above I would like to get two objects
of this class. If I had a single object returned by the API, I would've added a constructor which could consume JSON, but adding a method to parse an array of objects doesn't feel right.

REST Client class. This class is meant to make REST calls and deliver the result, I would like to make it re-usable, so I don't
want it to know anything about my model.

View controller. I would make the service call from here, then I want to parse the received data and display it on the view. Adding
the parsing logic here seems to be the most logical solution, but
doesn't feel quite right.

What are the good practices or design patterns for such a task? Do I need to create an extra class for this?

Thank you in advance.

答:
I would put the parsing code in a factory class that knows how to create both a single instance of the Model class from the JSON as well as how to create a sequence of Model class instances from the JSON.

This is based on the assumption that you already know what objects are being represented by the JSON. If you don't know exactly what objects the JSON represents, the factory class is the easiest mechanism that can be extented to take almost arbitrary JSON and create the correct objects for that.

The factory class would be used by your View controller, where you also receive the JSON.


答:
Most functional languages are not Object-Oriented.  That does not mean they have no objects (in the sense of complex types which have specific functionality associated with them).  Haskell, like java, has Lists, Maps, Arrays, all kinds of Trees and many other complex types.  If you look at the Haskell List or Map module you will see a set of functions very similar to the methods in most equivalent OO-language library modules.  If you inspect the code, you will even find similar encapsulation, with some types (or their constructors, to be precise) and functions only usable by other functions in the module.

The way you work with these types in Haskell is often hardly different from the OO way.  In Haskell I say

```<code>  null xs
  length xs
</code>```

and in Java you say

```<code>  xs.isEmpty
  xs.length
</code>```

Tomato, tomato.  The Haskell functions are not tied to the object but they are closely associated with its type. ¨Ah, but,¨ you say, ¨in Java it is calling which ever length method is appropriate to the actual class of that object¨.  Surprise - Haskell does polymorphism too with type classes (and other things).

In Haskell, if I have is - a collection of integers - it does not matter whether the collection is a list or set or array, this code

```<code>  fmap (* 2) is
</code>```

will return a collection with all the elements doubled.  Polymorphism means that the appropriate map function for the specific type will be called.

These examples are, in truth, not really complex types but the same applies in more difficult problems.  The idea that functional languages do not let you model complex objects and associate specific functionality with them is simply wrong.

There are important and significant differences between the functional and OO style but I don´t think this answer has to deal with them.  You asked if functional languages prevent (or hinder) intuitive modelling of problems and tasks.  The answer is No.

Body:
Most functional languages are not Object-Oriented.  That does not mean they have no objects (in the sense of complex types which have specific functionality associated with them).  Haskell, like java, has Lists, Maps, Arrays, all kinds of Trees and many other complex types.  If you look at the Haskell List or Map module you will see a set of functions very similar to the methods in most equivalent OO-language library modules.  If you inspect the code, you will even find similar encapsulation, with some types (or their constructors, to be precise) and functions only usable by other functions in the module.

The way you work with these types in Haskell is often hardly different from the OO way.  In Haskell I say

  null xs
  length xs

and in Java you say

  xs.isEmpty
  xs.length

Tomato, tomato.  The Haskell functions are not tied to the object but they are closely associated with its type. ¨Ah, but,¨ you say, ¨in Java it is calling which ever length method is appropriate to the actual class of that object¨.  Surprise - Haskell does polymorphism too with type classes (and other things).

In Haskell, if I have is - a collection of integers - it does not matter whether the collection is a list or set or array, this code

  fmap (* 2) is

will return a collection with all the elements doubled.  Polymorphism means that the appropriate map function for the specific type will be called.

These examples are, in truth, not really complex types but the same applies in more difficult problems.  The idea that functional languages do not let you model complex objects and associate specific functionality with them is simply wrong.

There are important and significant differences between the functional and OO style but I don´t think this answer has to deal with them.  You asked if functional languages prevent (or hinder) intuitive modelling of problems and tasks.  The answer is No.


问:
Dealing with error in data - Idempotent approach
A prior question had  an answer that interested me from a design perspective. I work in geospatial data and occasionally have to deal with voids when I read these binary files into my product. What is the best way to deal with voids when reading them in - throw an exception when you encounter them or return immediately. I believe one of the answers that I read talked of returning rather than throwing an exception. Currently I return rather than throw an exception. But I was wondering whether that is the best approach. </p>

答:
When deciding between throwing an exception or returning an error-code, there are a few considerations to take into account.

The primary one is how exceptional is the situation. Is receiving data with voids in them something that should not happen (and an indication that somewhere else something went really wrong), or is that something that your algorithm is supposed to be able to deal with gracefully. If it should not happen, then that is a strong indicator for using an exception.

A second consideration that I often use (and opinions are divided if it is a valid consideration) is if the immediate caller can be expected to resolve the problem. If I know beforehand that the immediate caller is unlikely to be able to do anything about an error I signal, except to pass the buck up the call chain, then I am more inclined to use an exception to report the error because it is less error-prone to let an exception go up the call chain than to report an error-code up several levels.


问:
Is it possible to make some methods invisible/non-usable to some classes in Java?
I am developing an application in Java whereby I would like to pass an object as part of an interface into other methods of classes written by other developers in the team. The object I'm passing in has setters and getters in the normal manner, but I don't want some of the classes written by others to access some of the setters of the object passed (different setters would be available to different classes when they use the object). Is this possible in Java? i.e. to define which classes may use which methods in other classes on a per-class basis?

I guess what I'd like to do is something like:

```<code>someObject.method(passInObject[but don't give access to passInObject.thisSetter])
</code>```

Where 'someObject' is an object of a class written by a team member, and 'passInObject' is an object from my class but I want to protect some of the members in it from this specific someObject class.

I'm guessing not and I will need to use inheritance to override those setters I don't want specific other modules to use/see, but it seems clunky to have a new inherited class per using class based on protecting some internal values from only some using classes. I could to a check in the code that a member's value hasn't been changed but that's too late and the damage is done (undoing may be expensive). I could check the name of the class in the setter method itself and do nothing if the name is on a 'banned' list, but that seems very clunky and error prone too. What I want is the calling code to restrict which members can be called in the passed object.

Or am I missing something and there is a common pattern to deal with this?

答:
Hiding inherited methods is a terrible idea and almost guaranteed to cause you grief.

I would say that this is what Interfaces are for; a "disclosure agreement" between two or more classes that accurately describes what each is allowed to know about the other[s].

Of course, this will get just a mite fiddly if its mixed with inheritance as you describe - should your base class implement the Interface or should each derived class do it for itself?  YMMV.


答:
Plenty of great developers take sabbaticals. Okay, okay, I just quit my job to take 2011 out as a self-funded sabbatical. ;)

But no, seriously, they do.

I've researched this topic a lot before coming to the decision to do it myself, and these are the basic findings: No, it's not a career ending move, but it's definitely a good idea to stay in practice and do something interesting during your gap year. If you take a year off to sit at home drinking beer and playing WoW, and come back and tell recruiters and hiring managers as much, it'll make you look exactly how it sounds. But if you take a year out to pursue some crazy and interesting adventure, and especially if you do something noble like volunteer work digging wells in Third World countries, then you'll be an interesting interviewee. Essentially, it pays to have a "good story" with some productive content, so the gap year doesn't sound like you just wanted to take time off to be lazy and do nothing.

Also, be careful about dropping completely out of practice with programming and technology. It's true that programming is mostly concepts and state of mind (and specific syntax is mostly is just that, syntax), but you still have to be careful not to come back and be all rusty and awkward in interviews. It's probably a good idea to, at the very least, do some refresher work (in the form of personal projects or maybe open source work) in the last couple of months of your gap year. The more the better, of course.

All that said, you probably should expect it to be a bit of a temporary career setback. Unless you have the reputation of a real rockstar programmer, you'll probably have to take a job that's a notch (in terms of seniority and pay) below what you could have had if you kept working and climbing the career ladder during that year. But it definitely doesn't have to be a career-ending move, unless you do all of the above spectacularly wrong.

Title: If you take a year or two out from being a developer, is it really that hard to get back into it?

Body:
I've been working as a developer for about 3 years now (straight from uni), I'm wondering, if I take a year or two out would it be impossible to get back into the industry?

I didn't get the gap year thing out of my system after uni, and I'm thinking that I should probably do it before I hit 30 (24 now), my main concern is that if I leave the industry now, I might not get back into it at all and end up working some dead end job.

The way I see things is, that general concepts / design patterns etc remain similar over the years, and it is mostly coding syntax / actual implementation that evolves, so it shouldn't move on dramatically.

Also, women developers (yes there are some out there!) take years out to have kids and still carry on with their career afterwards, so it can't be impossible.

Ultimatum : Would taking a year or two out destroy the (small) career I've built up so far?


问:
Is the 'finally' portion of a 'try ... catch ... finally' construct even necessary?
Some languages (such as C++ and early versions of PHP) don't support the finally part of a try ... catch ... finally construct. Is finally ever necessary? Because the code in it always runs, why wouldn't/shouldn't I just place that code after a try ... catch block without a finally clause? Why use one? (I'm looking for a reason/motivation for using/not using finally, not a reason to do away with 'catch' or why it's legal to do so.)

答:
finally blocks are usually used to clear up resources which can help with readability when using multiple return statements:

```<code>int DoSomething() {
    try {
        open_connection();
        return get_result();
    }
    catch {
        return 2;
    }
    finally {
        close_connection();
    }
}
</code>```

vs

```<code>int DoSomething() {
    int result;
    try {
        open_connection();
        result = get_result();
    }
    catch {
        result = 2;
    }
    close_connection();
    return result;
}
</code>```

Body:
finally blocks are usually used to clear up resources which can help with readability when using multiple return statements:

int DoSomething() {
    try {
        open_connection();
        return get_result();
    }
    catch {
        return 2;
    }
    finally {
        close_connection();
    }
}

vs

int DoSomething() {
    int result;
    try {
        open_connection();
        result = get_result();
    }
    catch {
        result = 2;
    }
    close_connection();
    return result;
}


答:
What would happen if and exception was thrown that you were not expecting. The try would exit in the middle of it and no catch clause is executed.

The finally block is to help with that and ensure that no matter the exception the cleanup will happen.

Title: Is the 'finally' portion of a 'try ... catch ... finally' construct even necessary?

Body: Some languages (such as C++ and early versions of PHP) don't support the finally part of a try ... catch ... finally construct. Is finally ever necessary? Because the code in it always runs, why wouldn't/shouldn't I just place that code after a try ... catch block without a finally clause? Why use one? (I'm looking for a reason/motivation for using/not using finally, not a reason to do away with 'catch' or why it's legal to do so.)


答:
That cannot be done. Your problems arise from violating ISP.

That said, the only idea I can think of is to force client classes to register with your classes in order to be able to call their methods or they get a NotRegisteredException. Once they register you can check their type and rise a YouAreNotAllowedToCallThisMethodException if the registered class is not in a list of allowed classes.

That's a very inelegant solution and I'd rather correct the ISP violations by segregating interfaces. But, that doesn't prevent your co-workers from using the interfaces you don't want them to use.

The following code examples are from this great answer by user Marjan Venema from another question.

```<code>interface IEverythingButTheKitchenSink
{
     void DoDishes();
     void CleanSink();
     void CutGreens();
     void GrillMeat();
}
</code>```

vs

```<code>interface IClean
{
     void DoDishes();
     void CleanSink();
}

interface ICook
{
     void CutGreens();
     void GrillMeat();
}
</code>```

Title: Is it possible to make some methods invisible/non-usable to some classes in Java?

Body:
I am developing an application in Java whereby I would like to pass an object as part of an interface into other methods of classes written by other developers in the team. The object I'm passing in has setters and getters in the normal manner, but I don't want some of the classes written by others to access some of the setters of the object passed (different setters would be available to different classes when they use the object). Is this possible in Java? i.e. to define which classes may use which methods in other classes on a per-class basis?

I guess what I'd like to do is something like:

```<code>someObject.method(passInObject[but don't give access to passInObject.thisSetter])
</code>```

Where 'someObject' is an object of a class written by a team member, and 'passInObject' is an object from my class but I want to protect some of the members in it from this specific someObject class.

I'm guessing not and I will need to use inheritance to override those setters I don't want specific other modules to use/see, but it seems clunky to have a new inherited class per using class based on protecting some internal values from only some using classes. I could to a check in the code that a member's value hasn't been changed but that's too late and the damage is done (undoing may be expensive). I could check the name of the class in the setter method itself and do nothing if the name is on a 'banned' list, but that seems very clunky and error prone too. What I want is the calling code to restrict which members can be called in the passed object.

Or am I missing something and there is a common pattern to deal with this?

Body:
That cannot be done. Your problems arise from violating ISP.

That said, the only idea I can think of is to force client classes to register with your classes in order to be able to call their methods or they get a NotRegisteredException. Once they register you can check their type and rise a YouAreNotAllowedToCallThisMethodException if the registered class is not in a list of allowed classes.

That's a very inelegant solution and I'd rather correct the ISP violations by segregating interfaces. But, that doesn't prevent your co-workers from using the interfaces you don't want them to use.

The following code examples are from this great answer by user Marjan Venema from another question.

interface IEverythingButTheKitchenSink
{
     void DoDishes();
     void CleanSink();
     void CutGreens();
     void GrillMeat();
}

vs

interface IClean
{
     void DoDishes();
     void CleanSink();
}

interface ICook
{
     void CutGreens();
     void GrillMeat();
}


答:
There are many ways to do that in Java depending on your specific scenario.

By one hand, we could start analyzing if access modifiers could help in this scenario.

For instance, in Java the package can be used to modularize your code.

```<code>package a;

public class A {
   private String foo;
   public String getFoo(){ return this.foo; }
   void setFoo(String foo){ this.foo = foo; }
}
</code>```

In the code above, only classes in the package A would ever be allowed to access the method setFoo since it is defined with a package-level access but everyone could invoke getFoo() since it is public.

If you know the users of your class will be in different package (which is the most typical scenario) than this would work perfectly for you. Use the package to define your cohesive modules and expose only what you want to be exposed.

If you want to hide functionality for the members of your own package than chances are that something could be wrong with the design maybe you need a subpackage or use more interfaces  as suggested in the other answer.

Body:
There are many ways to do that in Java depending on your specific scenario.

By one hand, we could start analyzing if access modifiers could help in this scenario.

For instance, in Java the package can be used to modularize your code.

package a;

public class A {
   private String foo;
   public String getFoo(){ return this.foo; }
   void setFoo(String foo){ this.foo = foo; }
}

In the code above, only classes in the package A would ever be allowed to access the method setFoo since it is defined with a package-level access but everyone could invoke getFoo() since it is public.

If you know the users of your class will be in different package (which is the most typical scenario) than this would work perfectly for you. Use the package to define your cohesive modules and expose only what you want to be exposed.

If you want to hide functionality for the members of your own package than chances are that something could be wrong with the design maybe you need a subpackage or use more interfaces  as suggested in the other answer.


答:
Try finally and try catch are two different things which only share the: "try" keyword.
Personally I would have like to see that different. The reason you see them together is because exceptions produce a "jump".

And try finally is designed to run code even if programming flow jumps out. Whether that be because of an exception or any other reason. It's a neat way to acquire a resource and make sure it's cleaned up after without having to worry about jumps.


答:
As others have mentioned, there's no guarantee that code after a try statement will execute unless you catch every possible exception. That said, this:

try {
   mightThrowSpecificException();
} catch (SpecificException e) {
   handleError();
} finally {
   cleanUp();
}
```

<p>can be rewritten<sup>1</sup> as:</p>

<pre class="lang-java prettyprint-override"><code>try {
   mightThrowSpecificException();
} catch (SpecificException e) {
   try {
       handleError();
   } catch (Throwable e2) {
       cleanUp();
       throw e2;
   }
} catch (Throwable e) {
   cleanUp();
   throw e;
}
cleanUp();
</code>```

But the latter requires you to catch all unhandled exceptions, duplicate the cleanup code, and remember to re-throw. So finally isn't necessary, but it's useful.

C++ doesn't have finally because Bjarne Stroustrup believes RAII is better, or at least suffices for most cases:

Why doesn't C++ provide a "finally" construct?

Because C++ supports an alternative that is almost always better: The "resource acquisition is initialization" technique (TC++PL3 section 14.4). The basic idea is to represent a resource by a local object, so that the local object's destructor will release the resource. That way, the programmer cannot forget to release the resource.

1 The specific code to catch all exceptions and rethrow without losing stack trace information varies by language. I have used Java, where the stack trace is captured when the exception is created. In C# you'd just use throw;.

Body:
As others have mentioned, there's no guarantee that code after a try statement will execute unless you catch every possible exception. That said, this:

try {
   mightThrowSpecificException();
} catch (SpecificException e) {
   handleError();
} finally {
   cleanUp();
}

can be rewritten1 as:

try {
   mightThrowSpecificException();
} catch (SpecificException e) {
   try {
       handleError();
   } catch (Throwable e2) {
       cleanUp();
       throw e2;
   }
} catch (Throwable e) {
   cleanUp();
   throw e;
}
cleanUp();

But the latter requires you to catch all unhandled exceptions, duplicate the cleanup code, and remember to re-throw. So finally isn't necessary, but it's useful.

C++ doesn't have finally because Bjarne Stroustrup believes RAII is better, or at least suffices for most cases:

Why doesn't C++ provide a "finally" construct?

Because C++ supports an alternative that is almost always better: The "resource acquisition is initialization" technique (TC++PL3 section 14.4). The basic idea is to represent a resource by a local object, so that the local object's destructor will release the resource. That way, the programmer cannot forget to release the resource.

1 The specific code to catch all exceptions and rethrow without losing stack trace information varies by language. I have used Java, where the stack trace is captured when the exception is created. In C# you'd just use throw;.


答:
Would taking a year or two out destroy the (small) career I've built up so far?

Not at all.

General knowledge you obtained will still be applicable in a year, in two years, in five years.

Current versions of software packages will get updates, but there won't be any tremendous progress you won't be able to catch in a few weeks of focused learning. And anyway the other programmer must learn new versions one after the other. No bad thing will happen if you omit a few versions that will have deprecated by the time you return.

Sometimes it is good to take a pause and return with a fresh eye on the things.

And yes, you could always describe the time off as learning something new or pursuing your own projects.


问:
Releasing libraries used in a commercial application as GPL
While I was at university I developed some PHP libraries which I intended for personal use. I used them in a few personal projects.

When I joined my current job we created a commercial product which required the same functionality. I proposed using my libraries as they were familiar to me. We did.

Since then I have modified and improved the libraries in the last couple of years (all in my own time) and want to release them as open source under the GPL licence.

Now under the GPL licence you cannot use the libraries as part of commercial software, so does me doing this now in any way affect the commercial software or their protection? Am I free to release these libraries in this way?

Thanks in advance!

答:
The license is intended to protect your copyright and interests, not to take them away.

As the only author of the library, you are free to relicense it under whichever scheme you wish, including for usage in commercial products. Indeed, it's not that uncommon. For instance, PolarSSL is released under GPLv2, but a license can be bought for usage in closed source code.

If the library is used internally (e.g. server-side) and never distributed, the relicensing thing is not even necessary, for GPLv3 at least.

The only issue would be if you used external code. In that case, you must take the necessary steps to comply with the respective license.


问:
Displaying copyright notice for OSS in closed source Android app
I am considering the usage of various open source libraries in a closed source Android app. The libraries are released under various licenses (MIT, BSD modern, Apache 2.0) which allow this kind of usage, but require that the copyright notice is made available verbatim with the application.

I have seen various approaches, at least four:

A submenu triggers a dialog where project names and relative licenses are displayed, e.g. Google apps.

A message like "This app uses various projects released under license XXXX" is displayed on the app website. No notice is present inside the application or in the Play Store description, e.g. Whatsapp.

No mention is done of the libraries being distributed with the application.

Like 3, but the APK contains a /license folder.

What is the best practice? Maybe something else? Are approaches #2 and #3 even in compliance?

As a passionate contributor to various open source projects, I would really go with #1. Unfortunately, I am not in charge, so I must be able to argue about #2 and #3 too and/or propose a better solution.

答:
The exact terms vary from license to license, but most licenses require that the copyright message is somewhere where the end-user can find them. You can not assume that a regular end-user visits your website. And it is even less reasonable to assume that a regular end-user will unpack the APK file to look for the license files. Android end devices usually do not even provide the tools for doing this.

That means having a menu entry where the user can read the open source licenses is the most reasonable option of those you provided. An about-section which also includes your own copyright notice is a good place for this.

Just because others take license terms lightly is no excuse that you should do the same. Not complying to the license terms opens you up to a lawsuit from the creators of the library. There are non-profit open source organizations which sometimes finance such lawsuits when the case is high-profile enough. Talk to your legal department for further information. You don't have a legal department? Get a lawyer. In todays world you can't do business without legal advise.


答:
You cannot do exactly what you want - see the other answers, but there are a couple of things you could do.

You could have a package private interface that exposes the setters, and a public interface that exposes the getters.

You mention that you want to use the setters in multiple packages in your own code. Why is this? This is a code smell for me - if your own code might mess with the internal workings of a class outside of the package where the class is defined, it sounds like you are breaking encapsulation and you should consider refactoring.

You could have a builder/factory object which releases immutable snapshots of these classes.

This is the preferred approach, especially if your application uses multithreaded code. Creating a POJO that contains all the data (but none of the mutability) of your original class will add the safety that you desire, plus it will make the code much easier to debug later.

No matter what you do, spending some energy on limiting the situations where shared objects can mutate, especially outside the package, will both help to address this problem and make your code easier to maintain later on.

Further reading:

Feature envy Martin Fowler

What is a" feature envy" code and why is it considered a code smell?


问:
Is brevity in writing code beneficial when it requires using language constructs in a strange way
In C#, with extension methods, you can replace this line of code:

```<code>TimeSpan interval = TimeSpan.FromMinutes(4);
</code>```

with this one:

```<code>TimeSpan interval = 4.Minutes();
</code>```

Extension method being:

```<code>public static TimeSpan Minutes(this int minutes)
{
    return TimeSpan.FromMinutes(minutes);
}
</code>```

The second example is interesting because of the extension method on the integer literal, which is valid, but looks strange (even more so because adding a period after a integer literal has two different meanings: becoming double literal and member access). The second example also reads almost like english (even though the first one does as well albeit in a different way).

Is it a bad practice to use language features in such way as to increase brevity and readability, but "abusing" the language? (I prefer answers that deal with WHY you consider one better than the other, and not only WHICH ONE you prefer.)

Personally I find the second way more like the usual object-oriented way of thinking in which you state the object first and then access its member operation to perform.

Similarly to how we do with ToString:

```<code>StringBuilder str = new StringBuilder();

// ... append something to the builder

String result = str.ToString();
</code>```

and we don't do

```<code>Strong result = String.From(str);
</code>```

Of course, one could argue that this is simply how the API/Framework was designed.

Additional note:

This can also be stretched toward some other examples of achieving brevity:

```<code>String str = String.Format("{0} + {1} = {2}", op1, op2, op3);
</code>```

changed to:

```<code>String str = "{0} + {1} = {2}".FormatWith(op1, op2, op3);
</code>```

答:
Is brevity in writing code beneficial when it requires using language constructs in a strange way?

Hell no.

Brevity is not a desirable trait. The time it takes to type in code is not a meaningful thing to optimize, since we so infrequently write code as opposed to read/debug/modify it. The time it takes the parser to read your code (or the size it takes on disk) is trivial.

Readability is a desirable trait, but it does not necessarily follow that brevity leads to readability. After all, the time spent understanding what we read isn't mostly spent on seeing characters, but parsing them into meaning. Doing weird things will take far longer to understand in general. This is well known as the Principle of Least Astonishment (or Surprise) in design circles.

Now sometimes, using weird constructs makes things more readable/efficient/robust once people learn them and get used to them. That is a trade-off like any other worth evaluating. But your examples all make things hard to read to do nothing more than save a few characters.


问:
haskell - are tuples defined recursively?

Are n-tuples defined recursively in terms of 2-tuples, for example, are (a,b,c) and (a,(b,c)) the same?

If not, what's the rationale behind it?

答:
1, No it's defined separately for each tuple. (So data (,) a b = (,) a b for the 2-tuple).
You can see the full list(and limit that you can use) here: https://downloads.haskell.org/~ghc/7.4.1/docs/html/libraries/ghc-prim-0.2.0.0/GHC-Tuple.html (also the comment about the number of n-tuples in the source is funny)

2, I would say performance but not sure about this.(Edit: see @itsbruce's answer for a better reason)


答:
It is possible that your mistake is taking a too fine-grained approach to access. Are you certain that each user of your class will have different access? Perhaps your actual problem is that you should be implementing a Role mechanism where only a user with a specific role can have access to certain methods.

A Role mechanism can be implemented using different interfaces or even using a Proxy for real fine-grained control.


答:
Most OSS licenses don't try to precisely prescribe what is expected, as they cannot reasonably know what environment they run in. After all, the freedom to run FOSS code in many environments is a fundamental part of what it means to be FOSS code.

Instead, there's usually a clause that relies on implicit or contextual norms. For instance, the requirement can be to display all the copyright information in one place. Hiding some of the relevant copyright information in another location, just because you don't own those copyrights can be seen as disingenuous. if you think your copyright belongs in dialog X, then you better place all copyrights there. If you find it acceptable to have only a link to a mobile webpage in your app, even for your own copyrights, it's likely the FOSS copyright owners will accept this.

Note that "contextual norm" can be set by third parties. If Apple decides to have a form where you need to state copyrights, then that becomes the norm for all iPhone apps, and you must list FOSS copyrights along with your own.

Title: Displaying copyright notice for OSS in closed source Android app

Body:
I am considering the usage of various open source libraries in a closed source Android app. The libraries are released under various licenses (MIT, BSD modern, Apache 2.0) which allow this kind of usage, but require that the copyright notice is made available verbatim with the application.

I have seen various approaches, at least four:

A submenu triggers a dialog where project names and relative licenses are displayed, e.g. Google apps.

A message like "This app uses various projects released under license XXXX" is displayed on the app website. No notice is present inside the application or in the Play Store description, e.g. Whatsapp.

No mention is done of the libraries being distributed with the application.

Like 3, but the APK contains a /license folder.

What is the best practice? Maybe something else? Are approaches #2 and #3 even in compliance?

As a passionate contributor to various open source projects, I would really go with #1. Unfortunately, I am not in charge, so I must be able to argue about #2 and #3 too and/or propose a better solution.


答: (a, (b, c)) is a 2-tuple whose second element happens to be another 2-tuple. If your suggestion had been adopted, it would not be possible to represent a tuple inside the final cell  of another tuple. Which would be a bizarrely asymmetric restriction and make tuples much less generally useful.

Title: haskell - are tuples defined recursively?

Body:
Are n-tuples defined recursively in terms of 2-tuples, for example, are (a,b,c) and (a,(b,c)) the same?

If not, what's the rationale behind it?


问:
Should an HTTP API always return a body?
Is there some sort of standard regarding HTTP API responses?

After reading this discourse thread I started to wonder.  We are developing our public HTTP JSON API at my work, and we do not return anything when it's not strictly needed (for example a PUT to /resource/{id} only returns 200 when OK or the corresponding 4XX or 5XX code, but no JSON body)

Should we return a generic {"success":true} like they discuss on that link above, or is it ok to return a "void" body and handle everything with http response codes?

答: No but it will help for consistency of your code. It also good for debugging purposes. It will also a big help in the maintenance of the website. Remember this: Error code is for machine, Error message is for human. So I am suggesting for you to use a response body. Anyway, its negative effect is just minimal(just a few bytes sent over the network) compared to its benefits. Another thing, it will also avoid you from forgetting to write a message body when it is needed.</p>