问:
What is the meaning of bootstrapping in software development?
In some articles and books that I read, I some time see the term 'Bootstrapping'. For example I see this sentence "Bootstrapping X.JS" in angular js document: http://docs.angularjs.org/tutorial/step_00

Bootstrapping AngularJS apps automatically using the ngApp directive is very easy and suitable for most cases. In advanced cases, such as when using script loaders, you can use imperative / manual way to bootstrap the app...

What is the meaning of bootstrapping in software development?

答:
Bootstrapping roughly means to create a self-sustaining system from scratch. In compiler development it is the practice of writing the compiler in the target language, then compiling the compiler with itself.

See the Wikipedia article on Bootstrapping.


答:
This is from Wikipedia:

bootstrapping usually refers to the starting of a self-sustaining
  process that is supposed to proceed without external input.

In angular means app automatically start with ngApp directive.

ContentLicense: CC BY-SA 3.0

Body:
In some articles and books that I read, I some time see the term 'Bootstrapping'. For example I see this sentence "Bootstrapping X.JS" in angular js document: http://docs.angularjs.org/tutorial/step_00

Bootstrapping AngularJS apps automatically using the ngApp directive is very easy and suitable for most cases. In advanced cases, such as when using script loaders, you can use imperative / manual way to bootstrap the app...

What is the meaning of bootstrapping in software development?


问:
Are problem-solving programming questions useful for improving one's general programming ability?
For example, like:

The inaugural International Olympiad in Frogleaping is being held in Australia in 2013 and you are determined to win. While you want nothing to do with such slimy, jumpy creatures, you plan to enter a frog-like robot that you know will be faster than all the other organic entrants.

The IOF takes place in a large pond in which there is a sequence of lily pads arranged in a long line. The rules of the race are simple: your frog will be placed on the first lily pad, then it must jump to the second lily pad, then the third and so forth until it reaches the last lily pad in the course. Note that you can not `skip' lily pads--every lily pad must be jumped on exactly once. The first frog to reach the last lily pad will win the race. Since your robotic frog has super-frog speed, you are confident in your victory.

However, your frog has one minor incorrectable flaw--it is only able to jump one fixed distance. Specifically, it can only jump exactly K metres forward from its current location, even if this lands the frog in the water (where it will promptly short-circuit).

Since the initial lily pad positions may make it impossible for your frog to reach the last lily pad, you plan to create a distraction and move the lily pads so that they are spaced exactly K metres apart, enabling your frog to jump from the first to the last without falling in the water. Shifting a lily pad by one metre will take you one second, and the longer you spend stealthily moving lily pads, the more likely that the IOF judges will notice and disqualify you from the competition.

Given the initial distances between the lily pads in the course, you must write a program to compute the minimum time you will have to spend shifting lily pads such that all pairs of consecutive lily pads are exactly K metres apart. You can assume that the pond is sufficiently long so that the first lily pad can be moved any distance back, and the last lily pad can be moved any distance forward.

Input

Your program should read from the file frogin.txt. The first line of this file will consist of two space-separated integers N and K. The following N-1 lines will contain the initial distances between consecutive pairs of lily pads. Specifically, the ith line will contain one integer representing the distance between the ith and (i+1)th lily pad.

Output

Your program should write to the file frogout.txt. Your output file should consist of one line containing one integer: the minimum total time spent shifting lily pads so as to ensure your victory.

This is a sample problem from the Australian Informatics Olympiad, which I happened to come across searching on the internet.

But I do not believe that any programming-related problems which do not directly connect with real-life situations will have any helpful effects upon one's real-world programming ability. Will they?

答:
Think about this:

first of all, to solve the given problem, there is a non-trivial program to be written. It does not need to have a fancy Web or desktop UI or a "database layer" or , but it involves some kind of "business logic" which has to be tested and debugged.

for solving the problem, you need some integer math / combinatorics. There are lots of real-world problems for which knowing integer math / combinatorics is helpful (of course, there is also a huge number of problems where you don't need this).

So IMHO yes, solving such problems teaches you certain aspects of beeing a better programmer. Of course, they don't teach you everything about real-world programming, especially nothing which involves a special technology. But the "Australian Informatics Olympiad" (or the Informatics Olympiad in other countries) is about informatics, not about real-world programming, so it has a different goal.


问:
Is it correct/useful to define Computational Complexity in this way?
I analyzed my algorithm and I deduced that in the best case it requires n^3 iterations while in the worst case it requires n^4 iterations. Then I asserted that my algorithm is in \Omega(n^3) and in \BigO(n^4). Is this assertion correct and useful?

(sorry for the format but I'm not able to add LaTeX text, so if you can please tell me how to format this I will edit soon, thanks)

答: It depends on what you do in each iteration. If you only perform at most a constant number of primitive computations in each iteration, then yes your running time is O(n^4). However, Theta(n^3) would mean that your running time has both the lower and upper bound n^3, which it does not. You can use Omega(n^3) to indicate the lower bound.


问:
How do you get developers to want to write good code they can be proud of?
In a team of developers, how do you get the developers to feel pride in their code and write good code (I realize this is subjective and everyone is different, but there is a point when I write code that i can say, this is a good piece of code that I am happy to show off).

To often I hear we have no time to write good code and all that matters is getting the defect fix closed. How do I change this outlook and make the coders create code they can be proud of.

This seems to be more prevalent in the younger coders, not all but most.

答:
Short answer:

If you don't have the time to do it properly now, will you have the time to do it properly later?

Long answer:

Maintenance is 70% of the effort in developing software. The more technical debt you build up in the code, the more maintenance effort is required. Bugs cost more effort to fix the longer they go unfixed, because of the need to reacquire knowledge about the code, the costs incurred by customers dealing with those bugs, the cost of deploying fixes, etc...

Delaying bug fixing is expensive. You have to break out of the negative feedback loop of "no time":

No time to write good new code, let's rush through it as best as we can and ship bad code

Bad code has lots of bugs, now we need to fix them

Since the bad code was written a while ago and the fix needs to be deployed to the customer, fixing it takes a long time

Because we spend so much time fixing bugs, we have no time to write new code

Goto 1

Consider trying to put a number on how much effort it costs to fix a bug on average, and then make it a goal to reduce that number. The way to do that is to write things properly in the first place, because fixing bugs while you write the code (e.g. detecting them through unit tests) is a lot cheaper for the organization as a whole than waiting until a tester (or the customer) finds them. If you have the right numbers to back you up, deciding to take the time to do the job properly can be defended financially to management (the only language they really care about).

It sounds like your team must first start to take ownership of their work. If they feel unable to make the decision to write proper code in the first place, you have to figure out why that is, and possibly negotiate with management to figure out a way to solve that. Once they feel enabled to make the necessary changes, change will happen. Nobody likes to be bad at what they do.


答:
This seems like 2 different questions: good code and being proud of your code. I'll just say something about the latter.

I'm almost never proud of what code I write as part of my job because:

the projects are not my idea, it's the customer's idea. They're rarely something cool or awesome and therefore it's really hard for me to feel excited about them.

the design and implementation of the project is a series of compromises: I have to agree to do it that way because otherwise that other module can't use my code; I have to agree to sacrifice some good design decisions because the rest of the team disagrees with them.

I think these aspects apply to most developers.

Probably the only way to make your developers proud of their code is to promote a culture in your company of "we deliver high quality products" versus "we deliver products fast and they work well enough". Making that change means delivering quality code which takes more time and therefore costs more. This is probably going to hurt your business, unless your business's foundation is quality, which it rarely actually is (HR and marketing bullsh*t almost never translates into real-world facts).

In software development, high quality code and business competitivity almost never go hand-in-hand. Just like you can't keep 2 dogs in the same bathtub :D .

Title: How do you get developers to want to write good code they can be proud of?

Body:
In a team of developers, how do you get the developers to feel pride in their code and write good code (I realize this is subjective and everyone is different, but there is a point when I write code that i can say, this is a good piece of code that I am happy to show off).

To often I hear we have no time to write good code and all that matters is getting the defect fix closed. How do I change this outlook and make the coders create code they can be proud of.

This seems to be more prevalent in the younger coders, not all but most.


答:
I think you are coming at the problem from the wrong viewpoint - the code is not the most important aspect of all this. The product is. You can have the most elegant, beautifully designed, most carefully crafted code that produces a useless, slow, buggy, un-usable product that is so badly documented no-one can understand or use it.

In fact, I'd say the "best" code always results in bad products because the developer is not focussed on making something that is simple and easy to maintain, that works according to the compromises required to make something practical. If you're too worried about all the little buzzword bits that are going around nowadays, you spend all your time trying not to repeat yourself or keep things separate that you forget the reason you're doing these.

Now this doesn't mean you should just hack whatever awful code together, but it does mean you need to focus the pride on the results. Results also include measures like communication and maintainability of code, not just working product BTW. For example, if there's no documentation that goes with it, and no-one can figure out how to use your beautifully complex OO API, then its no use to anyone.

So, how to encourage your young coders that pride in their work is a good thing. You can implement a system of feedback - if someone uses some code that they found easy to use or helpful, they can acknowledge the creator of that with a quick flag (similar to how sometimes a customer will send feedback concerning particularly good service). Then you can do code reviews - not the usual ones where the peers are involved, but where you pick a bug at random and go ask the developer to explain to you all about it, what they did, why they chose that approach, what supporting features they provided. Chances are you'll get the bare minimum and you can highlight what you expect, those that achieve your expectations can get a reward.


问:
Do Scrum sprints mean to work at the fastest pace possible?
I recently interviewed with some companies that do Agile, Scrum to be more precise and there are some things that don't quite seem like Agile to me. I'll take one case that particularly interests me right now, that of Scrum sprints.

One particular project manager I talked to (yes, I said project manager) proudly stated that people in her team understand ("were told" is what I picked up from the context) that you don't go home when the working hours are over, you go home when the job is done, no matter how much it takes. What I've read in between the lines is that we pack as much features as possible into a sprint and work overtime to make it happen.

Now, I haven't done Agile by now (worked with financial and governmental institutions which most still do prefer waterfall) but my understanding is that:

sprint in Scrum is the name for the generic iteration in Agile;

the team should work at a sustainable pace and try to avoid long term overtime as that has effects only on the short time and the effects are dwarfed by the problems they incur in the long time.

Are my statements right? And, should I take the manager's presentation as a red flag?

答:
No: scrum sprints are a timebox, nothing more, nothing less. At the start of the sprint / iteration, the team gives an estimate of the amount of story points they believe they can achieve, based on things like previous performance, availability, upcoming events, open impediments, etc. They then negotiate with the product owner about which user stories get put into the sprint. That is (or was? see other answer) the commitment the team gives to the product owner.

During development, if it turns out things aren't really as predicted (it is software development after all) and there is a risk the team will not meet the commitment, they inform the product owner that there is a risk one or more stories will not be completed.

And that's fine. Sure, it feels bad, having to admit at the end of the sprint that the sprint failed, but it's not defeat, it's an opportunity for improvement. Because at the end of the sprint / start of the new one, you get to do a sprint retrospective, and the first thing anyone will ask is 'Why did we fail this sprint, and what do we need to do to not fail it again?'. One option would be to give off less commitment (= take up less story points).

tl;dr: Sustainable Pace. Scrum is about cadence, something the team can keep up indefinitely on a sprint-to-sprint basis. Working overtime isn't; the team will become overworked, work will become sloppy, members will call in sick or quit altogether, and then you have a whole bigger problem than a failed sprint.


问:
Are optional parameters helpful or a hindrance to application maintenance?
As stated in the title, are optional parameters, such as those used in C# helpful or are they a hindrance to application maintenance and should be avoided as they can make the code harder to understand?</p>

答:
In general, if you need many/optional parameters often, your functions are doing too much, and should be broken up.  You're likely breaking SRP (Single Responsibility Principle).

Look for parameters that can be grouped, eg (x and y, become a point).

Are these optional parameters flags with a default?  If you're using flags, the function should be split up.

That's not to say you should never have optional parameters, but in general, more than one or two parameters suggest a code smell.

It could also be a clue that the function, should actually be a class, with the optional parameters changed to properties, and the required parameters part of the constructor.

ContentLicense: CC BY-SA 2.5


问:
How should I validate code when there is no one to do code review?
I'm used to working in a large development environment where code is peer reviewed and tested by the client, who is usually an IT person themselves. I am now working at a very small company where I'm not just the only developer, but the only IT person at all.

I'm inclined to have my coworkers and/or boss take a look at my work every time I finish a agile story, so they can either accept it or reject it, as is the pattern I'm used to. However, too often my coworkers either don't understand my work well enough to judge it or they misunderstand it and accept bad code or reject good code based on surface looks alone, like the color of links.

So I'm wondering how I should decide when to accept/reject tests now? Should I try to assess my own code like an outside person? Should I just skip it and accept everything? Should I try to educate my coworkers a bit and get them to do proper tests?

答:
If you are the only IT worker, then there's little point in getting anyone around you to review the code.  Nobody will have any idea what it means, and will just point out trivial stuff like spelling mistakes.

Make extensive use of unit tests.  Take heed of compiler warnings, and consider using automated code quality tools (but be prepared to ignore or turn off many useless warnings from them).

Only bother asking the people around you whether or not your code does what they want.  If it's confusing, or doesn't work for them, fix it.  If they are happy, then your code must be OK.


问:
Package diagram for an MVC patterned project?
We are required to make a package diagram for our senior project. Since our project uses MVC patter design, we created an MVC class diagram, now, our problem is in creating the package diagrams from our class diagram.

Is it possible to have packages with MVC at the same time? so it would be something like this:

Package: Account

Account Model

Profile Controller

Registration Controller

Profile View

Registration View

These are the controller that cannot exists without the Account model, so I included them.

Thanks in advance!

答:
Do not mix packages and components. Components do some common jobs, packages are merely "folders" in which the classes lie. You CAN do packages same as components, but it is very inconvenient.

So, the package diagram is very easy - you already have all your packages, only put there the connections about what belongs to which and who imports whom.

What you really need, is the component diagram, it is a level higher. Remember the main MVC rule - controllers can speak to anybody, Viewers and Models speak to Controllers only. Put components on the paper/screen and show by arrows, what information they are sending to each other.

Also you can move the components so, that M,V and C will be somehow clustered. And show these clusters, by color or by boundaries. But boundaries are usable only on easy diagrams, or you'll have too many lines.


问:
Testing my model for hybrid scheduling in Embedded Systems
I am working on a project for school, where I have to analyze the performances of a few fixed-priority servers algorithms (polling server, deferrable server, priority exchange) using a simulator in the case of hybrid scheduling, where we have both hard periodic tasks and soft aperiodic tasks.

In my model I consider that:

the hard tasks have a period equal to their deadline, with a known worst case execution time (wcet). The actual execution time could be smaller than the wcet.

the soft tasks have a known wcet and random interarrival times. The actual execution time could be smaller than the wcet.

In order to test those algorithms I need realistic case studies. For this reason I'm digging in the scientific literature but I am facing different problems:

Sometimes I find a list of hard tasks with wcet, but it is not specified how the soft tasks parameters are found.

Given the wcet of a task, how can I model its actual execution time? This means, what random distribution should I use considering the wcet?

How can I model the random interarrival times of soft aperiodic tasks?

答:
On the WCET - there is no definitive answer to this. WCETs tend to be highly pessimistic as, for a hard task, the task absolutely must be completed before deadline or your whole application is a failure (obviously firm tasks can allow some flexibility in this). I would suggest simply hard coding a distribution that ranges up to the WCET but where the bulk of tasks complete in something like 50% of WCET.

On the random inter-arrival times of soft tasks then a simple normal/binomial distribution of inter-arrival times should suffice. If you want to you can simply code this by giving the probability of the task arriving in a given period (eg 1 second) as  p  and set p to some value e.g., p=0.1 (in this case that means a mean inter-arrival time of 10 seconds). Then test against the value generated by your pseudo-random function (i.e., in this case if RND() or whatever gave less than 0.1 then your task arrives).

OwnerDisplayName: markusian


问:
How to depict Import a file action in the Sequence diagram
Everyone says sequence diagrams are so easy but I just cannot figure this out. Basically user clicks on an 'Import from temp folder' button, the program opens a window with a list populated with filenames, user clicks on a filename, clicks on OK and the document is imported.
I know the order of the actions but how to depict e.g. populating a list, or selecting an item from a list?

So I assume the objects would be like:

```<code>[USER]  [ImportDialogWindow]    [ListOfFiles:STRING]   [?where to go with selected file]
</code>```

答:
The file will be a message between these timelines. They will send it to each other.

But IMHO the sequence diagram on that low level for so simple tasks is excessive. Or the coder doesn't know, that he should read item and after that put it into a list?


问:
A programmer as project manager or non-programmer?
We are a team of programmers and are employing a new person who will be a project manager only. Our project are only programming ones and we are not sure how to decide who will be the best for project manager.

Shall we find a senior programmer from our programming field?

Or we must find a regular guy (economics or management studies) who never coded in his life?

EDIT

A project manager will_

Create tasks for developers

Monitor that our ticket workflow is respected

Warn developers is they cross estimated work time

Manage weekly finance timesheets

Help client and reply to his questions

Set meetings between client and developers (internet meetings)

And similar things.

Now, when I wrote this I see that there are no IT tasks in here. But what about simple questions the clients ask and which an educated It person will be able to reply? we obviously cannot bother programmers for this all the time. this is the main reason whay we are in doubt.

答:
A good project manager will focus on the product you're making - that it fulfils the requirements, and will provide direction on what those requirements will be. HE will also provide organisation to the team so it works productively on the things that matter.

Do you need such a guy? If so, a business-oriented chap is more likely to be used to this kind of role.

A senior programmer may not have enough experience or skill at managing customers, their requirements or organising the team.


答:
Yes, they are. I agree with Doc Brown, and I want to add that some problems (eg. ACM's ICPC) apart from math skills are also exercising your ability to model a problem, write an algorithm, etc.

Although most official submitted solutions are probably full of dirty hacks because of the time limits, you can take your time and solve the problems in an optimal and elegant way.

Title: Are problem-solving programming questions useful for improving one's general programming ability?

Body:
For example, like:

The inaugural International Olympiad in Frogleaping is being held in Australia in 2013 and you are determined to win. While you want nothing to do with such slimy, jumpy creatures, you plan to enter a frog-like robot that you know will be faster than all the other organic entrants.

The IOF takes place in a large pond in which there is a sequence of lily pads arranged in a long line. The rules of the race are simple: your frog will be placed on the first lily pad, then it must jump to the second lily pad, then the third and so forth until it reaches the last lily pad in the course. Note that you can not `skip' lily pads--every lily pad must be jumped on exactly once. The first frog to reach the last lily pad will win the race. Since your robotic frog has super-frog speed, you are confident in your victory.

However, your frog has one minor incorrectable flaw--it is only able to jump one fixed distance. Specifically, it can only jump exactly K metres forward from its current location, even if this lands the frog in the water (where it will promptly short-circuit).

Since the initial lily pad positions may make it impossible for your frog to reach the last lily pad, you plan to create a distraction and move the lily pads so that they are spaced exactly K metres apart, enabling your frog to jump from the first to the last without falling in the water. Shifting a lily pad by one metre will take you one second, and the longer you spend stealthily moving lily pads, the more likely that the IOF judges will notice and disqualify you from the competition.

Given the initial distances between the lily pads in the course, you must write a program to compute the minimum time you will have to spend shifting lily pads such that all pairs of consecutive lily pads are exactly K metres apart. You can assume that the pond is sufficiently long so that the first lily pad can be moved any distance back, and the last lily pad can be moved any distance forward.

Input

Your program should read from the file frogin.txt. The first line of this file will consist of two space-separated integers N and K. The following N-1 lines will contain the initial distances between consecutive pairs of lily pads. Specifically, the ith line will contain one integer representing the distance between the ith and (i+1)th lily pad.

Output

Your program should write to the file frogout.txt. Your output file should consist of one line containing one integer: the minimum total time spent shifting lily pads so as to ensure your victory.

This is a sample problem from the Australian Informatics Olympiad, which I happened to come across searching on the internet.

But I do not believe that any programming-related problems which do not directly connect with real-life situations will have any helpful effects upon one's real-world programming ability. Will they?


问:
Software on Budget and on time?
We've all (almost all) have heard about the horror stories as well as perhaps studied about them.

Its easy to find stories of software that is over budget and late.

I wanted to hear from developers the opposite story:

Question:

Do you know, or have worked on a project that was on budget and on time?

What is the most valuable lesson you learned from it?

答:
I had only one client in my life where all projects were completed on time and budget was steady -- It's my University where I studied and worked in a computer lab for science. For tasks, that most companies ask to finish in 1-2 months, in University we had a year. In companies they give you $N per hour, after a while they say "We lost some clients, dudes outside stole my bag with your salary, boss divorced with his wife and she wants a half of his biz, ..." etc. and your fee decreases by $K, then by $K again, and again. Until you think that you must pay for what you do. In University they have a tender for $XXX,XXX.XX divided on: rector, managers, you supervisor, some other people, your co-workers (mostly other students), and you.

Of course this is much less money than you can have in companies, but for a risk you should pay.

Title: Software on Budget and on time?


问:
How to deliver 3 different parameters to class in one method (2 of 3 are optional)
I need your help how to implement it nice and well. It's quite a simple problem. I can solve it but I need help on how to do that better.

My class has logic working using three parameters. It gets them from another class. The problem is:

the first parameter is enum (it's required)

the second parameter is another enum (it's optional - there is possibility that this parameter doesn't exist)

the third parameter is vector of other enums (it's optional - there is possibility that this parameter doesn't exist).

How to handle these parameters to my class?

Any ideas?

I'd like to get these parameters in one method, e.g. updateParameters(...).

Maybe I should have overloaded methods for every possibility, but it's not nice I guess. I can't get some container with parameters because I have different types.

答:
As a rule of thumb when creating an enumeration, some value is left for NONE (usually 0). In cases similar to yours this value is passed in to indicate that no other value suites. Adding such value to your enums will solve the problem with optional parameters.

In case of vectors of enums, you can always pass in an empty vector.

I wouldn't consider overloading methods for different cases unless this cases require completely different handling. Even in that case you could consider a public method with all parameters and then create private methods for handling specific cases based on optional parameters.


问:
Object inheritance and method parameters/return types - Please check my logic
I'm preparing for a test and doing practice questions, this one in particular I am unsure I did correctly:

We are given a very simple UML diagram to demonstrate inheritance: I hope this is clear, it shows that W inherits from V and so on:

```<code>                  |-----Y
V <|----- W<|-----|
                  |-----X<|----Z
</code>```

and this code:

```<code>public X method1(){....}
method2(new Y());
method2(method1());
method2(method3());
</code>```

The questions and my answers:

Q: What types of objects could method1 actually return?

A: X and Z, since the method definition includes X as the return type and since Z is a kind of X is would be OK to return either.

Q: What could the parameter type of method2 be?

A: Since method2 in the code accepts Y, X and Z (as the return from method1), the parameter type must be either V or W, as Y,X and Z inherit from both of these.

Q: What could return type of method3 be?

A: Return type of method3 must be V or W as this would be consistent with answer 2.

答:
Method3() result can belong to V or W. So, it can be of any type, as any type here belong to V.

Others two are OK


问:
Do activity diagrams always end in one endpoint?
For example an activity diagram for a simple program:

Get User data.

If User Exists DO something, ELSE do nothing.

End.

I often see diagrams with multiple endpoints but also with just one. Should activity diagrams merge both ways to one final state, regardless of the previous paths?

答: Here you are speaking on one timeline only. But even in it there could be many end points - due to branching. And on the diagram you can have many timelines, each with its endpoints. On your timeline one endpoint will be enough, but we can say nothing about other timelines.</p>


答:
There are three sensible solutions here:

You could pass them as parameters to your constructor, the first parameter being the required parameter, or..

You could create getters and setters to provide these parameters afterwards, or..

You could pass a map containing property values.

Passing to constructor

Passing to the constructor indicates that while optional, they must be made known immediately upon construction of the instance.  If this is not your case, I would avoid it entirely since A) you may not immediately have that information upon initialization and B) you want to convey a class's usage as best as possible and thus there's no point to limit when it is not necessary.

Using getters and setters

For me at least, using getters and setters tells me that you're using an optional parameter.  As such, I don't feel obliged to provide some value just to ensure that one is provided.  This is best if these values are truly optional, however, and a parameter's default will work fine as is.  If you think the caller would be better off setting it to something (despite being optional), then you should probably stick with passing to constructor.

Please note that you should only be prepared to use getters and setters if you're willing to allow changes at any point of an instance's usage.  By this I mean that should you set parameters using a setter, call execute, then change that parameter later and call execute a second time, it should work as expected, using whatever value it is currently set to.  If you cannot guarantee this, you should not use getters and setters (use passing to constructor method above).

Also, for what concerns your vector of enums, consider the possibility of adding a "add" method which takes a single enum value or a vector and adds it to its internal enum vector.  This is also comfortable if you have one value so you don't have to create a vector simply to add new values.

Property map

A property map is a good idea if you see yourself having to serialize these values to a database or on a file somewhere.  It is also handy if you think the properties passed may vary significantly.  I generally prefer to avoid this method, however I tend to use it when I'm dealing with properties that my class doesn't have to be familiar with but are still important to subclasses.  An example of this is if I were to instantiate a database connection and I don't need to know all the properties which may pertain to that particular connection.

Conclusion

I hope this gives you a start.  Generally speaking, I try to use getters and setters for all optional parameters if I can.  Anything which must be necessary immediately upon creation of a new instance (default or otherwise) absolutely has to be in the constructor.

You can also mix and match these techniques.  The impression I give to the caller at that point would be a mix as well.  In other words, if I put parameters in constructor and also provide setters and getters, the message I want to pass is "These parameters should be known immediately as they don't have suitable defaults, however you can later change them."  If I use property map with getters and setters, the message I want to pass is "Some of these parameters are static and optional, while others are dynamic and may contain more information than this class can deal with."

Edit:  I'm not sure what you mean by updateParameters.  If all these parameters will potentially change from one moment to the next, then you should consider creating an entirely new instance each time.  If only some parameters may change, then you can use getters and setters and change whichever parameters are different with respect to before.

Title: How to deliver 3 different parameters to class in one method (2 of 3 are optional)

Body:
I need your help how to implement it nice and well. It's quite a simple problem. I can solve it but I need help on how to do that better.

My class has logic working using three parameters. It gets them from another class. The problem is:

the first parameter is enum (it's required)

the second parameter is another enum (it's optional - there is possibility that this parameter doesn't exist)

the third parameter is vector of other enums (it's optional - there is possibility that this parameter doesn't exist).

How to handle these parameters to my class?

Any ideas?

I'd like to get these parameters in one method, e.g. updateParameters(...).

Maybe I should have overloaded methods for every possibility, but it's not nice I guess. I can't get some container with parameters because I have different types.


问:
Why can python webapps keep sessions between restart and not java?
I've used both webapp2 + GAE for python and a number of Java/JEE webapp frameworks. The python WSGI framework could keep users logged in while I redeploy the app while none of the Java web framework that I tried could do it. If I redeploy, users of the Java webapp will get logged out but if I use GAE for python then a redeployment doesn't log users out. Is this a general "feature" of python vs Java webapps and is this true in general or just a coincidence that the ones I tried had these features? Is there a name for this feature, ability to keep users logged in between redeployments and also keeping caches (e.g. memcache) without getting the cache erased for updating the app=</p>

答:
You're not looking hard enough. Pretty much all java servers that I know of are able to persist sessions. Its just a case of reading the docs and setting up the config.

See this answer for tomcat.


问:
How can I indicate if an object operates with another one in an UML class diagram?
Suppose I want to draw a class diagram of a DAO and an Entity. The DAO is used to load instances of the Entity from the database. How can I represent this relationship on my class diagram? Is this considered one? I think it should be displayed on the diagram somehow:

TL;DR: should I draw something between them or not?

答:
DAO loads data from DB and CREATES instances of Entity:

There is a special stereotype for such dependency. Class INSTANTIATES Class2, if it creates its instances. Exists in UML standard. ( I checked 2.4.1 - contemporary and 2.5 - the next one.)


问:
How do you annotate instantiation in UML class diagrams?
Given this pseudo code:

```<code>class B { }

class A : B
{
    int val;
};

alpha = new A();
</code>```

What arrow do I draw between alpha and A in a UML class diagram? Is this even something UML is meant to do?

```<code>+-------+        +-------+        +-------+
| alpha | --??-- |   A   |------|>|   B   |
|       |        |       |        |       |
+-------+        +-------+        +-------+
</code>```

In my case, I truly do want to express explicitly that alpha instantiates A. So if there is no way in UML, I'll just make up a way -- which is fine, but I want to know if UML can express it already. My situation is that I'm trying to explain OOP to a friend who is very visual. Therefore, I want to try to visually distinguish the two relationships (inheritance and instantiation) so that he can distinguish it mentally.

答: There is a special stereotype for such dependency. Class INSTANTIATES Class2, if it creates its instances. Exists in UML standard. ( I checked 2.4.1 - contemporary and 2.5 - the next one.)


问:
SOA: should I always consider it?
While I think how to direct the future development:

Mini-introduction

As a fixed rule, I start with SOA (and REST as protocol) then I work on the interfaces (and that interface is a customer of my service, and usually is a separate project). I assume my deviation is because I'm first of all a back-end developer (with poor drawing skills).

Considering:

The BIGs are making a great effort in making quick and easy to use tools for creating interfaces. (I am referring to projects such as the bootstrap, angular, android studio, and many others); This is a relief for those who develop platforms, opens the door to many new applications for their platforms.

MV*, JSON, Javascript are becoming a standard in building (even) complex applications; It does not matter if the interfaces are all the same, the boilerplate today have reached a level that can be considered viral.

The increasingly common repository of modules (ex. NPM), enable even novice programmers the use and implementation of external APIs with great ease.

fate can always kiss our products and this maybe become the new facebook (with this I am referring to the fact that a product, even if required as a standalone, it can easily attract the interest of many, and it is very likely that new interfaces are required out of the initial planning).

Questions:

Is SOA an approach that architects (and programmers) should encourage and consider starting new design?

Is SOA the most suitable architecture to react to unplanned expansion?

答:
Is SOA an approach that architects (and programmers) should encourage and consider starting new design?

Services Oriented Architecture (SOA) is an approach worth considering, but it is not an end-all, be-all methodology.  Nor was it ever truly intended to be despite over-zealous marketing.  SOA is useful in large environments where you can have a high order of n:n interactions from various applications and other services.  Using an SOA approach in this case makes it easier to encapsulate your offering and shield its internals from public view.

But in other environments SOA is not the right approach at all.  For example, an embedded developer may not be able to afford the overhead SOA incurs within their selected chipset.

Is SOA the most suitable architecture to react to unplanned expansion?

Maybe; maybe not.  It depends upon where the change creeps in.

SOA does a great job of masking change that is internal to the service.  So long as the service's interface or API is maintained then callers don't care how it's actually implemented.

In cases where the change involves the interface, SOA doesn't do a great job of masking those changes.  Since services are intended to be designed without much / any knowledge of the caller then it can be harder to implement a change at the interface layer.  A non-SOA approach has more knowledge of the callers and that makes it easier to identify what additional areas need to be modified or tested based upon the changes.

Part of the challenge here is that Public APIs are forever.

Title: SOA: should I always consider it?


答:
This question is primary opinion based, and the following is just my opinion.

Shall we find a senior programmer from our programming field? Or we must find a regular guy (economics or management studies) who never coded in his life?

It's a little alarming that you didn't list previous project management experience as your first requirement, and that you need a project manager who has experience managing software projects.

What would happen if a project manager said "We need to hire a programmer, but our projects are always late. To solve that problem I'll hire a project manager who knows a little about programming as our new programmer."

Hire a project manager that specializes in managing software projects. Don't hire someone who sees project management as a temporary step in their career.

```<code>Create tasks for developers
Monitor that our ticket workflow is respected
Warn developers is they cross estimated work time
Manage weekly finance timesheets
Help client and reply to his questions
Set meetings between client and developers (internet meetings)
</code>```

There are two ways you can handle this. Have the software developers tell the project manager what his job is, or hire a project manager that will tell the software developers what their job is.

A technically knowledgeable manager will quickly gain the respect of fellow team members, but with that said. A non-technical manager who knows how to manage a team can gain the respect of the business owner.

It all depends on who the project manager is accountable too.

Large corporate companies can often afford to hire project managers that are highly technical and work closely with software teams. Smaller companies are more focused on the bottom line, and need project managers who manage costs first. Technical issues is why they hired the technical people.

Title: A programmer as project manager or non-programmer?

Body:
We are a team of programmers and are employing a new person who will be a project manager only. Our project are only programming ones and we are not sure how to decide who will be the best for project manager.

Shall we find a senior programmer from our programming field?

Or we must find a regular guy (economics or management studies) who never coded in his life?

EDIT

A project manager will_

Create tasks for developers

Monitor that our ticket workflow is respected

Warn developers is they cross estimated work time

Manage weekly finance timesheets

Help client and reply to his questions

Set meetings between client and developers (internet meetings)

And similar things.

Now, when I wrote this I see that there are no IT tasks in here. But what about simple questions the clients ask and which an educated It person will be able to reply? we obviously cannot bother programmers for this all the time. this is the main reason whay we are in doubt.

Body:
This question is primary opinion based, and the following is just my opinion.

Shall we find a senior programmer from our programming field? Or we must find a regular guy (economics or management studies) who never coded in his life?

It's a little alarming that you didn't list previous project management experience as your first requirement, and that you need a project manager who has experience managing software projects.

What would happen if a project manager said "We need to hire a programmer, but our projects are always late. To solve that problem I'll hire a project manager who knows a little about programming as our new programmer."

Hire a project manager that specializes in managing software projects. Don't hire someone who sees project management as a temporary step in their career.

Create tasks for developers
Monitor that our ticket workflow is respected
Warn developers is they cross estimated work time
Manage weekly finance timesheets
Help client and reply to his questions
Set meetings between client and developers (internet meetings)

There are two ways you can handle this. Have the software developers tell the project manager what his job is, or hire a project manager that will tell the software developers what their job is.

A technically knowledgeable manager will quickly gain the respect of fellow team members, but with that said. A non-technical manager who knows how to manage a team can gain the respect of the business owner.

It all depends on who the project manager is accountable too.

Large corporate companies can often afford to hire project managers that are highly technical and work closely with software teams. Smaller companies are more focused on the bottom line, and need project managers who manage costs first. Technical issues is why they hired the technical people.


答:
When you are working in small companies, its normal to have to wear several hats.  Take the most extreme example, when the company is first created, you still have developer, tester, analyst, sales, book keeping, marketing etc...  roles, but probably only 2 or 3 people to share the work.

In this case, its quite possible that you are doing the analysis of what is required, developing, testing, deploying, maintaining and supporting.  Whilst its preferable for there to be multiple people covering these roles from both a quality and business continuity perspective, in a small company that may be an expensive luxury.

The best advice I can give is to always be clear about what the roles are, and to think as though you are performing each of these roles when you are performing their tasks on the project.  Over time this process will become more fluid, and you will become more comfortable with thinking ahead and handling the competing responsibilities.

If I was currently your manager, I would be looking to see if you can step up to the challenge ahead and take ownership.

Title: How should I validate code when there is no one to do code review?

Body:
I'm used to working in a large development environment where code is peer reviewed and tested by the client, who is usually an IT person themselves. I am now working at a very small company where I'm not just the only developer, but the only IT person at all.

I'm inclined to have my coworkers and/or boss take a look at my work every time I finish a agile story, so they can either accept it or reject it, as is the pattern I'm used to. However, too often my coworkers either don't understand my work well enough to judge it or they misunderstand it and accept bad code or reject good code based on surface looks alone, like the color of links.

So I'm wondering how I should decide when to accept/reject tests now? Should I try to assess my own code like an outside person? Should I just skip it and accept everything? Should I try to educate my coworkers a bit and get them to do proper tests?


问:
Are problem-solving programming questions useful for improving one's general programming ability?
For example, like:

The inaugural International Olympiad in Frogleaping is being held in Australia in 2013 and you are determined to win. While you want nothing to do with such slimy, jumpy creatures, you plan to enter a frog-like robot that you know will be faster than all the other organic entrants.

The IOF takes place in a large pond in which there is a sequence of lily pads arranged in a long line. The rules of the race are simple: your frog will be placed on the first lily pad, then it must jump to the second lily pad, then the third and so forth until it reaches the last lily pad in the course. Note that you can not `skip' lily pads--every lily pad must be jumped on exactly once. The first frog to reach the last lily pad will win the race. Since your robotic frog has super-frog speed, you are confident in your victory.

However, your frog has one minor incorrectable flaw--it is only able to jump one fixed distance. Specifically, it can only jump exactly K metres forward from its current location, even if this lands the frog in the water (where it will promptly short-circuit).

Since the initial lily pad positions may make it impossible for your frog to reach the last lily pad, you plan to create a distraction and move the lily pads so that they are spaced exactly K metres apart, enabling your frog to jump from the first to the last without falling in the water. Shifting a lily pad by one metre will take you one second, and the longer you spend stealthily moving lily pads, the more likely that the IOF judges will notice and disqualify you from the competition.

Given the initial distances between the lily pads in the course, you must write a program to compute the minimum time you will have to spend shifting lily pads such that all pairs of consecutive lily pads are exactly K metres apart. You can assume that the pond is sufficiently long so that the first lily pad can be moved any distance back, and the last lily pad can be moved any distance forward.

Input

Your program should read from the file frogin.txt. The first line of this file will consist of two space-separated integers N and K. The following N-1 lines will contain the initial distances between consecutive pairs of lily pads. Specifically, the ith line will contain one integer representing the distance between the ith and (i+1)th lily pad.

Output

Your program should write to the file frogout.txt. Your output file should consist of one line containing one integer: the minimum total time spent shifting lily pads so as to ensure your victory.

This is a sample problem from the Australian Informatics Olympiad, which I happened to come across searching on the internet.

But I do not believe that any programming-related problems which do not directly connect with real-life situations will have any helpful effects upon one's real-world programming ability. Will they?

答:
Usually when people rant against a problem's relevance, that means they find it too hard.  It's by solving difficult problems that you grow.  The best you get from repeatedly solving easy problems is you get faster at solving easy problems.

Those sorts of problems are meant to be fun, but that doesn't mean they aren't relevant to a programmer's daily work.  Some examples of problems that are similar in terms of algorithms and thought process, but more "serious" are:

Creating an animation to evenly space out elements placed roughly on a display.

Calculating the latency to handle events that arrive at irregular times, but that you wish to handle evenly-spaced.

Compensating for jitter in streaming audio or video.


问:
I am a beginner. Can I directly start learning C++11? or I have to learn old C++?
I'm a beginner and have only little knowledge in programming.

Would it be good if I directly learn C++ from books which cover new C++11 or should I study through the old best C++ books?

Should I have little knowledge about C++ before learning C++11? or I can start directly from there?

Would it cause problem if I directly start from C++11? If no, then suggest some books on C++11.

答:
C++ Is a really great and powerful language. However it also places a lot of responsibility on the programmer.

If you are completely new to programming, make life easier for yourself and start with C#.  It's syntax is based on C++, but the error handling is much more beginner friendly in assisting you when things go wrong.

If you are comfortable with methods, classes, inheritance and are wanting to develop in an environment where managing memory and system resources is more important than productivity, then C++ is a good choice, and I would start by learning the current standard.  Bare in mind that C++ requires you to understand memory and to actively manage it. Make mistakes here, and all you get is either a core dumped, or your data contains bytes that don't make sense.  And often the point where you find the problem is unrelated to where the cause actually is.


问:
How to refresh/keep up to date content in the browser without overloading the server
I am not very educated on this topic of programming so I am seeking any advice/knowledge. I am coding a web app in PHP, and this particular task requires updating the display after the server has new information available. So, one seemingly-bad solution is to have a repeating AJAX request that spams the server on an interval, and updates when it gets new data. This puts a lot of stress on the server, so it seems unviable to me.

We attempted to use Ratchet (http://socketo.me/) but could not really figure it out. Is this overcomplicating this, or is there another way we can solve this problem while still keeping server load as "practically" minimal as possible. There are websites like Facebook/most social media that dynamically show new data as it's available -- I assume they also use something that minimizes requests to the server? Or is this assumption incorrect?

答:
Big question: how quickly does the display on the client need to update when there is new data on the server? Within 1 second? 10 seconds? 1 minute?

Another big question: how many clients do you expect might use your system at the same time?

If the client needs to be updated within a fraction of a second, then yes, polling the server (using repeated AJAX requests) is probably a bad idea. If 10 seconds, 30 seconds, or even a couple minutes response time is OK, then polling will probably be fine.

Assuming your data is in a relational DB, make sure there are indexes in place which can be used to retrieve the "new" data quickly. If you are not using a relational DB, understand the performance implications of how your particular DB accesses data, and do whatever is necessary so the "new" data can be accessed quickly, without much computation OR I/O.

(For reference: I recently built a system with clients which poll the server every 3 minutes -- I have an updated_at timestamp on all the records which the client is interested in, and an index on the timestamp. When the server sends data to the client, it also sends  a timestamp which tells it "this data is valid as of such-and-such a time". Next time the client polls for more data, it sends the timestamp it received so the server can retrieve the records which have been updated in the meantime.)


问:
Is eventual consistency a wrong solution for e-commerce applications?
I'm reading about eventual consistency in couchDB. I'm somewhat confused by the term and its consequences on an application.

Let's say I'm building a distributed e-commerce website where monetary transactions are critical. There could be online auctions running and people bidding on them in real time.
Will using a eventual consistent DB such as couchDB be a wrong solution? Should I favor a more consistent solution such as a relational database?

Is couchDB suitable for something non critical such as a social network where one wouldn't mind if his news feed isn't up to date or when comments on his posts are somewhat delayed by few seconds?

Update

I'm talking about building a distributed system. I think in case of a single server nothing of this will matter.

答:
Think of it this way:

You can use eventual constancy to record and capture each users bids.  The fact that the database will take a few mSec to share the bids around is not material.

You can also have a stand alone process that decides which auctions have finished, and which bid won each auction.  This process needs to allow a few seconds for eventual consistency to complete so that it is highly likely to have a complete view of all bids.  However its decision needs to be final.

The users then can see who has been awarded the auction as per normal. The fact that some users may see this a few mSec earlier than the others again is not material, the key is that if they keep refreshing their page (or receive push messages) they will see it when the replication has made it to their database server.


问:
Martin Fowler's Refactoring book: switch statement is using other object's data, why is that bad ? A deeper explanation is sought for.
In the code sample below the Rental object is using Movie's fields to do a switch statement. Martin says : this is a bad idea but he does not give any deeper explanation as to why ?

Of course, you can say that this means a lot of coupling between Movie and Rental, or that Movie is badly encapsulated but those are just (almost meaningless) words, again, they don't explain the why? They don't go to the root of the question, so to say. They don't provide much understanding.

What I would like to know if there is a deeper, more general design principle why having a switch on Rental is a bad idea ?

In other words, how does Martin knows that the switch statement is on the wrong object ? Where does he get this insight from ? What is his thought process ?

答:
Why is relying upon the properties (or fields) of a another class to make a calculation a bad idea?  The answer is inherent in the title of the book: refactoring.  If changes are made to that class, the scope and meaning of the data can change.  If a new movie type/price code is created, this code also needs to be adjusted.

Which points out the more precise problem -- relying upon a enum/type in another class.  If Rental used a Renter class that had an age, and offered discounts based upon age, that wouldn't be such a problem.  Age is unlikely to change.  If on the other hand, our hypothetical Renter class had a Renter.Type (corporate, family, individual, minor, senior citizen), that would be much more likely to get modified, thus breaking Rental.

OwnerDisplayName: jhegedus


问:
How do you get developers to want to write good code they can be proud of?
In a team of developers, how do you get the developers to feel pride in their code and write good code (I realize this is subjective and everyone is different, but there is a point when I write code that i can say, this is a good piece of code that I am happy to show off).

To often I hear we have no time to write good code and all that matters is getting the defect fix closed. How do I change this outlook and make the coders create code they can be proud of.

This seems to be more prevalent in the younger coders, not all but most.

答:
There are three main areas that need to be addressed to handle such a broad problem. You may not be able to change all of them.

Business Strategy: sales, marketing, etc. - Getting to market sooner may just trump everything else. When you don't even know if anyone will buy your product, you take more risks in the area of technical debt. Customers who hate implementing your next release because you have a history of creating new bugs is just as bad as those who don't think you release fast enough and are willing to accept a few flaws.

Management, rewards and punishments. - If the only thing anyone recognizes is how many bugs everyone fixes in a fixed amount of time, that's the system everyone will learn to game. Is anyone aware that these quick-fixes introduce new bugs? Do you constantly have to push back on adding new features because the code is too difficult to understand which makes maintenance and enhancement more difficult? When it doesn't fit the Business is when it causes the most problems.

Training and Mentorship - Inexperienced devs (they don't have to be young) probably continue to program in the same way as the tutorials they learned from and what worked well enough on some smaller project. They have to be trained and that rarely gets done by someone else or on their own. It's too expensive to find and hire entry-level programmers, to just let them learn on their own. If they're not capable of learning from the mistakes pointed out in your code reviews (you have code reviews?) or unwilling to follow your coding standards (do you have any?), then you may be forced to replace them.

All of these are intertwined. I'm not sure those who program heart pacemakers are any better than those building social websites as long as they understand and work within the framework of the Business Strategy, Management and Training.


问:
What's the best way to retrieve a value and a status
Given that all else is equal, and there are no coding standards defining the best approach, what would be the recommended way in C++ to check that a value exists and return it if it does?

For example, something like one of these declarations:

```<code>bool getMethod(double& ret);

double getMethod(bool& ok);

void getMethod(bool& ok, double& ret);

pair<bool, double> getMethod();

bool checkMethod(); // eg if (checkMethod())
double getMethod(); //        result = getMethod();
</code>```

or something else, like return a struct

The value may exist about 50% of the time.

The existing code already does a lot of the last method, i.e. using a checkMethod() but I was wondering if that's really an efficient way to do it - via two calls (half the time).

答:
The problem here is that you are trying to create a function that does 2 things. Check if a value exists. Return an existing value. The best advice I can give is to separate your concerns. Write functions that do just one thing. In this case you might right functions such as:

```<code>bool HasValue()const; // returns true if the value exists
double GetValue()const; // returns the value, and throws an exception if the value does not exist.
</code>```

In this way you have 2 clear methods that do exactly what they say they will do. They each do 1 task.

Body:
The problem here is that you are trying to create a function that does 2 things. Check if a value exists. Return an existing value. The best advice I can give is to separate your concerns. Write functions that do just one thing. In this case you might right functions such as:

bool HasValue()const; // returns true if the value exists
double GetValue()const; // returns the value, and throws an exception if the value does not exist.

In this way you have 2 clear methods that do exactly what they say they will do. They each do 1 task.


问:
Why define a Java object using interface (e.g. Map) rather than implementation (HashMap)
In most Java code, I see people declare Java objects like this:

```<code>Map<String, String> hashMap = new HashMap<>();
List<String> list = new ArrayList<>();
</code>```

instead of:

```<code>HashMap<String, String> hashMap = new HashMap<>();
ArrayList<String> list = new ArrayList<>();
</code>```

Why is there a preference to define the Java object using the interface rather than the implementation that is actually going to be used?

答:
Having the variable constrained to an interface ensures none of the usages of that variable will be using HashMap specific functionality that may not exist on the interface, so the instance may be changed without concern later to a different implementation so long as the new instance also implements the interface.

For this reason, anytime you want to use an objects interface, it is always good practice to declare your variables as the interface and not the particular implementation, this goes for all types of objects you may use which have an interface. The reason you see it often is many people have built this in as a habit.

That said, it's not harmful to skip out of using interfaces sometimes, and most of us sloppily don't always follow this rule, with no real harm. It's just a good practice to stick to when you have any feeling the code may be changed and need maintenance/growth in the future. It's less of a concern when you're hacking on code you don't suspect will have a long life or has much importance. Also breaking this rule usually has a small consequence  that changing the implementation to another one may require a bit of refactoring, so if you don't always follow it you won't hurt yourself a lot, though there's no real harm in following it either.


答:
The reason is that the implementation of these interfaces is usually not relevant when handling them, therefore if you oblige the caller to pass a HashMap to a method, then you're essentially obliging which implementation to use.  So as a general rule, you're supposed to handle its interface rather than the actual implementation and avoid the pain and suffering which might result in having to change all method signatures using HashMap when you decide you need to use LinkedHashMap instead.

It should be said that there are exceptions to this when implementation is relevant.  If you need a map when order is important, then you can require a TreeMap or a LinkedHashMap to be passed, or better still SortedMap which doesn't specify a specific implementation. This obliges the caller to necessarily pass a certain type of implementation of Map and strongly hints that order is important.  That said, could you override SortedMap and pass an unsorted one?  Yes, of course, however expect bad things to happen as a result.

However best practice still dictates that if it isn't important, you shouldn't use specific implementations.  This is true in general.  If you're dealing with Dog and Cat which derive from Animal, in order to make best use of inheritance, you should generally avoid having methods specific to Dog or Cat.  Rather all methods in Dog or Cat should override methods in Animal and it will save you trouble in the long run.

Title: Why define a Java object using interface (e.g. Map) rather than implementation (HashMap)

Body:
In most Java code, I see people declare Java objects like this:

```<code>Map<String, String> hashMap = new HashMap<>();
List<String> list = new ArrayList<>();
</code>```

instead of:

```<code>HashMap<String, String> hashMap = new HashMap<>();
ArrayList<String> list = new ArrayList<>();
</code>```

Why is there a preference to define the Java object using the interface rather than the implementation that is actually going to be used?


问:
SQL Update statement generator using C# Winforms?
I am trying to make an UPDATE STATEMENT generator using C# Winforms. I would like to build a statement generator which will print statements like this:

UPDATE Customers
SET ContactName='Alfred Schmidt', City='Hamburg'
WHERE CustomerName='Alfreds Futterkiste';
```

But my problem is, how can I let the user paste in multiple values for each SET? My end user is likely to build a list using a spreadsheet and will want to paste in the values into a multi-line text box.  I could create 2 multi-line text boxes, but what if i have more SET columns i need to add?

答: Place simple text fields, check if user entered anything, then check/avoid SQL injection attempts, then replace 'Alfred Schmidt' with value1, etc.</p>


答:
It's to follow the interface segregation principle (the 'I' in SOLID).  It prevents code that uses those objects from depending on methods of those objects it doesn't need, which makes the code less coupled, and therefore easier to change.

For example, if you find out later you really need a LinkedHashMap, you can safely make that change without affecting any other code.

However, there's a trade off, because you're artificially limiting the code that can take your object as a parameter.  Say there's a function somewhere that requires a HashMap for some reason.  If you return a Map, you can't pass your object into that function.  You have to balance the likelihood of sometime in the future needing the extra functionality that's in the more concrete class  with the desire to limit coupling and keep your public interface as small as possible.


问:
Is it a bad idea to return different data types from a single function in a dynamically typed language?
My primary language is statically typed (Java).  In Java, you have to return a single type from every method.  For example, you can't have a method that conditionally returns a String or conditionally returns an Integer.  But in JavaScript, for example, this is very possible.

In a statically typed language I get why this is a bad idea.  If every method returned Object (the common parent all classes inherit from) then you and the compiler have no idea what you're dealing with.  You'll have to discover all your mistakes at run time.

But in a dynamically typed language, there may not even be a compiler.  In a dynamically typed language, it's not obvious to me why a function that returns multiple types is a bad idea.  My background in static languages makes me avoid writing such functions, but I fear I'm being close minded about a feature that could make my code cleaner in ways I can't see.

Edit: I'm going to remove my example (until I can think of a better one).  I think it's steering people to reply to a point I am not trying to make.

答:
Using Generics in Java allows you to return a different type, while still retaining static type safety.  You simply specify the type that you want to return in the generic type parameter of the function call.

Whether you could use a similar approach in Javascript is, of course, an open question.  Since Javascript is a dynamically typed language, returning an object seems like the obvious choice.

If you want to know where a dynamic return scenario might work when you are used to working in  statically-typed language, consider looking at the dynamic keyword in C#.  Rob Conery was able to successfully write an Object-Relational Mapper in 400 lines of code using the dynamic keyword.

Of course, all dynamic really does is wrap an object variable with some runtime type safety.


答:
In general, it's a bad idea for the same reasons the moral equivalent in a statically typed language is a bad idea: You have no idea which concrete type is returned, so you have no idea what you can do with the result (aside from the few things that can be done with any value). In a static type system, you have compiler-checked annotations of return types and such, but in a dynamic language the same knowledge still exists - it's just informal and stored in brains and documentation rather than in source code.

In many cases, however, there is rhyme and reason to which type is returned and the effect is similar to overloading or parametric polymorphism in static type systems. In other words, the result type is predictable, it's just not quite as simple to express.

But note that there may be other reasons a specific function is badly designed: For example, a sum function returning false on invalid inputs is a bad idea primarily because that return value is useless and error-prone (0 <-> false confusion).

Title: Is it a bad idea to return different data types from a single function in a dynamically typed language?

Body:
My primary language is statically typed (Java).  In Java, you have to return a single type from every method.  For example, you can't have a method that conditionally returns a String or conditionally returns an Integer.  But in JavaScript, for example, this is very possible.

In a statically typed language I get why this is a bad idea.  If every method returned Object (the common parent all classes inherit from) then you and the compiler have no idea what you're dealing with.  You'll have to discover all your mistakes at run time.

But in a dynamically typed language, there may not even be a compiler.  In a dynamically typed language, it's not obvious to me why a function that returns multiple types is a bad idea.  My background in static languages makes me avoid writing such functions, but I fear I'm being close minded about a feature that could make my code cleaner in ways I can't see.

Edit: I'm going to remove my example (until I can think of a better one).  I think it's steering people to reply to a point I am not trying to make.


答:
Your question makes me want to cry a little.  Not for the example usage you provided, but because someone will unwittingly take this approach too far.  It's a short step away from ridiculously unmaintainable code.

The error condition use case kind of makes sense, and the null pattern (everything has to be a pattern) in statically typed languages does the same type of thing.  Your function call returns an object or it returns null.

But it's a short step to saying "I'm going to use this to create a factory pattern" and return either foo or bar or baz depending upon the function's mood.  Debugging this will become a nightmare when the caller expects foo but was given bar.

So I don't think you're being closed minded.  You're being appropriately cautious in how use the language's features.

Disclosure: my background is in statically typed languages, and I have generally worked on larger, diverse teams where the need for maintainable code was fairly high.  So my perspective is probably skewed as well.


答:
In Layman's words:

The same reason electric apliances makers built their products with electrical plugs instead of simply peeled out cables, and houses come with wall sockets instead of peel out cables sticking out of the wall.

By using standard plugs instead, they allow to plug the same apliances in any compatible plug around the house.

From the point of view of the wall socket, it doesn't matter whether you plug a TV set or a stereo.

That makes both the appliance and the socket more useful.

Take for example a method that accepts a Map as an argument.

The method willl work regardless of you passing a HashMap or a LinkedHashMap to it, as long it's a subclass of Map.

That's Liskov substitution principle.

In the sample code you gave, it means you can later, for some reason, change the concrete implementation of Hash and you will not need to change the rest of the code.

The problem with software is that, since it's relatively easy to change things later with no waste of bricks or mortar, people assume that kind of fore-thought is not worth the while. But reality has showed us that software maintenance is very expensive.


答:
What I think (being a developer, not a manager), one thing is enough: allow them do TDD (and do not prohibit pair-programming). They will do such code, then.

But that's of course, only true for developers for want to write high quality code, but are not allowed by strict rules.

If you need to motivate people who "are good with anything that seems it's working", I can't help you :-( .


答: It's a bad idea, I think, to return different types conditionally. One of the ways this comes up frequently for me is if the function can return one or more values. If only one value needs to be returned, it may seem reasonable to just return the value, rather than packing it in an Array, to avoid having to unpack it in the calling function. However, this (and most other instances of this) places an obligation on the caller to distinguish between and handle both types. The function will be easier to reason about if it's always returning the same type. </p>


问:
Implementing an interface from a framework vs simple java interface
This concept is unclear with me.

I have worked on several frameworks for an instance Spring. To implement a feature we always implement some interfaces provided by the framework.

For an instance if I have to create a custom scope in Spring, my class implements a org.springframework.beans.factory.config.Scope interface. Which has some predefined low level functionality which helps in defining a custom scope for a bean.

Whereas in Java I read an interface is just a declaration which classes can implement & define their own functionality. The methods of an interface have no predefined functionality.

```<code>interface Car
{
topSpeed();
acclerate();
deaccelrate();
}
</code>```

The methods here don't have any functionality. They are just declared.

Can anyone explain this discrepancy in the concept? How does the framework put some predefined functionality with interface methods?

答:
There is no difference between how a framework handles interfaces and how your code does. There is a concept called Interception. Frameworks often times have classes that intercept calls on interfaces and run their own code before or after your implementation runs.

A simple roll-your-own way to do interception in a framework that you are writing would be to use the decorator pattern. Many DI frameworks provide a means of doing interception and use more sophisticated ways of accomplishing it such as through the use of reflection.


答:
By contrast to other answers, there are cases where returning different types is acceptable.

Example 1

```<code>sum(2, 3) → int
sum(2.1, 3.7) → float
</code>```

In some statically typed languages, this involves overloads, so we can consider that there several methods, each one returning the predefined, fixed type. In dynamic languages, this may be the same function, implemented as:

```<code>var sum = function (a, b) {
    return a + b;
};
</code>```

Same function, different types of return value.

Example 2

Imagine you get a response from an OpenID/OAuth component. Some OpenID/OAuth providers may contain more information, such as the age of the person.

```<code>var user = authProvider.findCurrent();
// user is now:
// {
//     provider: 'Facebook',
//     name: {
//         firstName: 'Hello',
//         secondName: 'World',
//     },
//     email: 'hello.world@example.com',
//     age: 27
// }
</code>```

Others would have the minimum, would it be an email address or the pseudonym.

```<code>var user = authProvider.findCurrent();
// user is now:
// {
//     provider: 'Google',
//     email: 'hello.world@example.com'
// }
</code>```

Again, same function, different results.

Here, the benefit of returning different types is especially important in a context where you don't care about types and interfaces, but what objects actually contain. For example, let's imagine a website contains mature language. Then the findCurrent() may be used like this:

```<code>var user = authProvider.findCurrent();
if (user.age || 0 >= 16) {
    // The person can stand mature language.
    allowShowingContent();
} else if (user.age) {
    // OpenID/OAuth gave the age, but the person appears too young to see the content.
    showParentalAdvisoryRequestedMessage();
} else {
    // OpenID/OAuth won't tell the age of the person. Ask the user himself.
    askForAge();
}
</code>```

Refactoring this into code where every provider will have its own function which will return a well-defined, fixed type would not only degrade the code base and cause code duplication, but also will not bring any benefit. One may end up doing horrors like:

```<code>var age;
if (['Facebook', 'Yahoo', 'Blogger', 'LiveJournal'].contains(user.provider)) {
    age = user.age;
}
</code>```

Body:
By contrast to other answers, there are cases where returning different types is acceptable.

Example 1

sum(2, 3) → int
sum(2.1, 3.7) → float

In some statically typed languages, this involves overloads, so we can consider that there several methods, each one returning the predefined, fixed type. In dynamic languages, this may be the same function, implemented as:

var sum = function (a, b) {
    return a + b;
};

Same function, different types of return value.

Example 2

Imagine you get a response from an OpenID/OAuth component. Some OpenID/OAuth providers may contain more information, such as the age of the person.

var user = authProvider.findCurrent();
// user is now:
// {
//     provider: 'Facebook',
//     name: {
//         firstName: 'Hello',
//         secondName: 'World',
//     },
//     email: 'hello.world@example.com',
//     age: 27
// }

Others would have the minimum, would it be an email address or the pseudonym.

var user = authProvider.findCurrent();
// user is now:
// {
//     provider: 'Google',
//     email: 'hello.world@example.com'
// }

Again, same function, different results.

Here, the benefit of returning different types is especially important in a context where you don't care about types and interfaces, but what objects actually contain. For example, let's imagine a website contains mature language. Then the findCurrent() may be used like this:

var user = authProvider.findCurrent();
if (user.age || 0 >= 16) {
    // The person can stand mature language.
    allowShowingContent();
} else if (user.age) {
    // OpenID/OAuth gave the age, but the person appears too young to see the content.
    showParentalAdvisoryRequestedMessage();
} else {
    // OpenID/OAuth won't tell the age of the person. Ask the user himself.
    askForAge();
}

Refactoring this into code where every provider will have its own function which will return a well-defined, fixed type would not only degrade the code base and cause code duplication, but also will not bring any benefit. One may end up doing horrors like:

var age;
if (['Facebook', 'Yahoo', 'Blogger', 'LiveJournal'].contains(user.provider)) {
    age = user.age;
}


问:
Emulating communication between Android and microcontroller using threads or services or... other?
I am not sure what is the best way for the tasks below: threads, AsyncTasks, Loopers, services? Why? Are there other candidates?

I need threads/Tasks/Services/other for:

Plotting data, (refreshing should be done let's after after specific amount of data has been read)

Generating data, (must being done during whole application runtime indefinitely)

Reading data, (as above)

Saving data on SD card / doing some logs

Interacting with UX

More detailed scenario I must emulate communication between an external device and Android.
External device (I don't have access to that device for some time - I am waiting for it to arrive, that's why I want to emulate the communication - which is a control and measurement system board with ARM microprocessor) generates some data packed in frames in ASCII format.
Android needs to pool? (Maybe there's a way to say: "Hey I have generated data for you. Take it!"? - If yes, could you advise me?) the external device to read data.

答:
Let's look at the options:

AsyncTask - Allows something to perform background work and publish results on a UI thread. Designed for you to use with something short that needs to happen in the background which once complete immediately updates the UI.

Loopers - Essentially is a construct that helps you implement queue processing on a thread. So, others can send your thread messages that are added to a queue which you then handle sequentially.

Services - Essentially an app that runs in the background and doesn't have a user interface. Once started, can continue running.

Threads - I think you understand this. Asyc within your app. Dies with your app.

So, to answer your question, a thread will be best. An external device is running independently of your application code, but only interacts with the phone while your app is running. So, it doesn't need to be emulated as a service (completely unnecessary) and should be not done as an AsyncTask - you're not emulating UI interactions (I assume). A Looper may be helpful, but it depends on the specific interaction between app and device. Your description suggests you want something to independently generate the events that your application handles (with potentially bidirectional traffic between the two). Using a Looper would require that you code both your application and external device as separate threads, then use Loopers on each to manage queued communication between the two.

So, whether you use the Looper construct or not, you'd still need to emulate your external device in a thread. Furthermore, a Looper would introduce a further level of indirection and abstraction between your app and actual device. I'm sure when you get to working with the actual device, you'd like to modify your application code as little as possible. Using a Looper, you'd need to write a thread that handles communication through the Looper construct. Since the actual communication will likely already be either asynchronous or through another synchronous (threaded) library, emulating it as a thread makes it easy to use the same semantics as the final implementation (you won't need to add on a Looper wrapper or remove the one from your app and test/debug a different interface layer).


问:
What are the disconnected scenarios in Entity Framework?
I'm not sure I understand what all fall under the disconnected context scenarios in EF (See this and this). This link says use Web API or WCF services to avoid the complexities of disconnected tier EF solutions.

Here's my understanding. If I create a new DbContext, get some entities, pass it to another process/machine (anything outside the scope of the current context), and there I make some changes to these entities and try to save them, then this is a disconnected scenario. EF will not know whether it is an Add or Update or what fields have changed, unless I explicitly tell it.

Suppose I have an MVC app, with a UserController. The UserController takes in a IUsserService through dependency injection. UserService, the concrete implementation of IUserService takes in a UnitOfWork. My DbContext is instantiated for the UnitOfWork, and SaveChanges() is called only on Commit() of the UnitOfWork. I also set the lifetime of the DbContext in Unity as PerRequestLifetime -> which means one instance is created for each HttpRequest. My UserService works with different entities required to do its job. I believe this is not a disconnected scenario, since my context is the same throughout?

If my MVC controller were in one machine (web), and the UserService in another machine(app - http endpoints exposed using webapi), does anything change? In this case, I need the DbContext only starting with ApiController, and everything will stay within the app layer. So I still avoid disconnected contexts. Am I right?

If I'm not clear, I can put some code, but nothing different in there.

答:
The words "disconnected context" refer to the fact that most modern web applications  only connect to the database long enough to retrieve and store data for the lifetime of a single web page.  While they might maintain a session, they do not typically maintain a persistent database connection like a client/server application does.

Basically what they are saying is that there are now better facilities for handling disconnected data scenarios, such as Web API and WCF Services.  These services handle all of the complexity behind the scenes of storing and retrieving data (with your programming help, of course), while maintaining a front-facing API that is REST compliant.


问:
Can I use machine learning for screening experimental data?
I am a experimental physicist. In our research, we have our experimental data in a 400*400*400 matrix(x, y, z axis of a 3d space), each entry is associated with a value("brightness"). We expect the brightest entries will form a closed path in the 3d space. But some portion of the path is always too dark to identify, also there are some noise in the space(random bright lines).

Our current algorithm generates random seed points into the space, they are attracted by the brightness of the data. After certain amount of time, they will be trapped in the path. If we record the seed points position we can get the path. Our current algorithm does a fairly good job while I still need to manually add those relatively dark points to the path.

I am not familiar with machine learning, but I am wondering if it can be used on this case? For example, is it possible that I tell the program which data points are on the path, the program will know how to choose the data points for the path in the future. Or if there is some other method we can use? Thanks!

答:
Yes, sounds like what you want to do is basic machine learning. Sorry, I can't comment yet.

Essentially, you need to be able to (in the future with real data) do a good job of discriminating between dark points not actually on a path and dark points on a path. So, you need to train a classifier that discriminates between path and not path.

Amon, each datum is (x, y, z, brightness). Furthermore, you have points around each other. So a classifier or clustering algorithm [by definition, machine learning] would look at not only the brightness of a given point, but what the other points are doing around it.

Support vector machines may be a good classifier to start with. You may need to search around or ask in your CS dept for introductory resource material. Your problem difficulty is such that I feel you are more than capable of having a classifier up and running within a week or two of working on this. I don't know any online tutorials offhand, I typically refer to my intro to machine learning notes whenever I need a "simple" refresher.


问:
Why should an "Order" object have a "Status" property?
I always see standard Order classes implemented with a "Status" property, but I don't feel comfortable with that. Isn't the status a property of the fulfillment process instead of the order itself? What about orders that can be subject to different fulfillment processes?</p>

答:
Isn't the status a property of the fulfillment process?

No, it's the status of an order, unless you plan on attaching a fulfillment process to the order.  Normally, that's not how it works; think of a fulfillment process as a "factory" that processes orders.  A property on such a process might look like "how many orders are currently in the shipment queue?"

Your customer isn't going to look up a fulfillment process when he wants to know what the status of his order is; he's going to look up his order.  As the programmer, you're going to want to maintain that status in the Order record (or an OrderStatus table), not some fulfillment process (although the list of possible statuses may be influenced by that process).


答:
Isn't the status a property of the fulfillment process instead of the order itself?

Not necessarily.  The fulfillment process may have a contributing status for the Order, but it's possible that there are multiple fulfillment processes.  Final status needs to remain with the Order.

What about orders that can be subject to different fulfillment processes?

Exactly.  You've provided the counter example showing why Status should belong to the Order.  Think about how you would track an order that was fulfilled through two separate processes.  Work on the order could be complete in one fulfillment route but not even started within another.

Title: Why should an "Order" object have a "Status" property?

Body: I always see standard Order classes implemented with a "Status" property, but I don't feel comfortable with that. Isn't the status a property of the fulfillment process instead of the order itself? What about orders that can be subject to different fulfillment processes?</p>


问:
Operating systems theory -- using minimum number of semaphores
This situation is prone to deadlock of processes in an operating system and I'd like to solve it with the minimum of semaphores.  Basically there are three cooperating processes that all read data from the same input device. Each process, when it gets the input device, must read two consecutive data. I want to use mutual exclusion to do this.  Semaphores should be used to synchronize:

```<code>P1:                     P2:                     P3:
input(a1,a2)            input (b1,b2)           input(c1,c2)
Y=a1+c1                 W=b2+c2                 Z=a2+b1
Print (X)               X=Z-Y+W
</code>```

The declaration and initialization that I think would work here are:

semaphore s=1

sa1 = 0, sa2 = 0, sb1 = 0, sb2 = 0, sc1 = 0, sc2 = 0

I'm sure that any kernel programmers that happen on this can knock this out in a minute or 2.

Diagram of cooperating Processes and one input device:

It seems like P1 and P2 would start something like:

wait(s)

input (a1/b1, a2/b2)

signal(s)

答:
Your process description seems to suggest that P1 needs data read by P3 (c1), P2 needs data read by P3 (c2), and P3 needs data read by P1 and P2 (a2 and b1).

So, is this what needs to happen (where * can occur anytime after 2):

P1 <- read a1

P3 <- read c1

P3 <- read c2

P2 <- read b1 and b2
*. P1 <- read a2

Or do P1, P2, and P3 use a cache of the last value read in the other process?

If the latter, you just need one mutual exclusion semaphore to control access to the device. If the former, you can have a fourth process that handles reading all the data and synchronize on when a valid set is available for all the use and when the data set has been read by all parties.

The fourth process doesn't have to know ahead of time what the data to be read is, it can simply implement a message queue where P1, P2, and P3 send it the parameters for data to be read. It then incrementes a counting semaphore each time it completes reads from each process. After sending their read message, everyone waits until the "data ready" semaphore reaches 3, then knows a valid set of data is available. After doing a read, they in turn increment a "data read" semaphore and wait for it to reach 3. When it does, they then wait on the "data ready" semaphore to go to 0 (the fourth process handles this after everyone has signaled their read, setting the "data ready" semaphore back to 0 then the "read data" semaphore back to 0. and the whole process repeats itself. Note, you'd never have a case where a process could miss the transition back to zero (deadlock) since each process needs to signal that their read is complete before the wait for "data ready" to go to zero by the time the third process gets around to doing it's read.

So, bottom line, you should be able to implement this with either 1 semaphore or 2 depending on what your requirements are for a concurrent set of data.

EDIT - Reviewing this, the "data ready" semaphore doesn't need to be a counting one since the thread with sole ownership of the input device can simply keep an internal count and just signal once when a complete data set is ready.