答:
I've designed and obseved others design multiple systems in the past and I've seen the process unfold in many different ways, but what I find common is that the initial architecture should at least plan for the existance of most major features.

For example I've seen an HVAC control system that had no concept of buildings, floors, rooms etc being retrofitted with those and the result was as ugly as they come. Or a mobile music device built out from components better suited for your (non-smart) pocket watch. Needless to say the end products in either case weren't customers' favorites.

When you say "conception" that's only one step up from "idea" and a concept can be very fuzzy. Business usually cares about concepts. Customers usually care about UX - a concept brought to reality in a way that's easy and pleasant to use and brings some value through its use.

You have to do "concept" before any programming, I can't envision myself opening visual studio (or your IDE of choice) and randomly writing code, to see where it goes.

You may not do a complete design (and you shouldn't) before coding but you should have a rough sketch of what the user's workflow would be.

UX design and coding quite often feed off each-other, you'll likely be forced to use some Agile approach for anything but smallest of projects as a way to incorporate this fact into how you approach the work. So don't think you're the worst of programmers if you couldn't see it all at once - nobody can and the people who think they can are the ones who just ignore enough of the problem so they can claim they have a complete picture.

One example to put a size to something big.
Concept: "Create a visual cloud-based tool that allows businesses to integrate their software platforms". This sounds great and one can start writing up marketing material and sell it before it's even there. You have to have this before coding.

Pre-design: "Have shapes and arrows like in Visio to describe logic; have plug-in capabilities to allow connections to various platforms (SAP, SF, databases...); have a monitoring console where one can search data passing through the system; have a way of describing data visually and transform one format to another". Another great marketing blob. It also gives you some ideas on what's important, should have such a rough sketch before coding too.

Design/Code: "Have a browser hosted HTML designer with such and such features; code the backend in Java so it can run on any existing server; define data structures and UX for querying or modifying them as needed; plan for disaster recovery, error reporting, audit logging; plan version control; plan access control;...." - the finer the list the more unrealistic it is to foresee all of it.

... however one should be at least aware of what things might end up looking like roughly or your final product may end up with some really useless implementations that end up killing the otherwise great-sounding concept - say your visual designer requires a 40" screen to show any real-world workflow, or there's no way to search the logs other than an exact string match limited to one of the 20 fields in the log etc etc. There's no good way to prevent this from happening other than executing your implementation - some will succeed, others will fail.


问:
Checking program robustness using static code analysis
(Building on  this question)

If you have a static code analyser such as Checkstyle, is it possible to to relate any of the stuff that it checks for to actual robustness? Some of the things that Checkstyle checks for are e.g.:

Class design: Visibility of class members, enforcing public only static final members, no public constructors for utility classes, exceptions are immutable etc.

Coding: Inline conditionals, no empty statements, no illegal instantiation and magic numbers

Duplication: Checks for code duplication,

Import: Checks that packages are imported correctly

Metrics:  Checks everything from the number of times logical operators have been used in a statement to the number of classes that the given class relies on other classes (coupling) etc.

Naming Conventions: Checks many properties of variable name, package names, method names, class names etc

These are just some of the main things that Checkstyle checks for. Could any of these areas actually help "improve" the robustness of the code by detecting "errors" ? I mean sure it helps with the readability and other code smells, but I can't see how I can relate it to robustness.

Do you need to look at code in run-time to actually inspect robustness issues?

答:
Code that is well-designed and well-written is more robust, because it minimizes edge cases and rabbit holes that are more prevalent in code that doesn't follow "best practices."

Static analysis helps code robustness for the same reasons that static types do; you catch problems earlier in the coding cycle, because the compiler will tell you you're doing it wrong.  Folks who use dynamically-typed languages benefit from a more relaxed coding style, but must compensate for the lack of static typing by writing more unit tests.

ContentLicense: CC BY-SA 3.0


问:
How to write a good mock for testing
I code in Python and I'm starting to use the Mock library.

Although I've read through all of the documentation, something that I'm finding hard to understand is 'What makes a good mock'.

For example, say I've got a function that makes a HTTP request:

```<code>def fetch_url(url, method=urlfetch.GET, data=''):
    """Send a HTTP request"""

    result = urlfetch.fetch(url=url, method=method, payload=data,
                            headers={'Access-Control-Allow-Origin': '*'})

    return result.content
</code>```

What would a good mock for this function look like? Furthermore, what would then be tested?

From my understanding, the characteristics of a good test are that the test checks:

That the code isn't broken

That the code acts as expected

That the code returns the expected output if it returns something

That said, what would be the characteristics of a good mock?

答:
A good mock:

acts as a stand-in for an object dependency of the unit under test.

provides meaningful "fake" behavior for that object dependency.

Isolates the unit under test from the real dependency (which has its own tests).

Not very exciting, is it?

The very best mocks are the ones that write themselves, with the help of a mocking library like Moq or Rhino Mocks.  The documentation for these libraries gives a pretty good overview of how, when and where to best use mocks.

Title: How to write a good mock for testing


问:
Javascript, JQuery and now AngularJS What is happening?
I have been away from computers for about 3 years and starting to get back into programming. Lots has changed in resources and help sites available on the web especially the evolving StackExchange community. I come from the IRC #javascript, #html, #php days with php.net and a bit of google search finds here and there.

With that said, before I took my break from programming JQuery was around but not nearly as common as today. I personally stay away from it finding it easier to just write what I need done in traditional javascript.

Now I have just stumbled across AngularJS. I do not know much about it, just looked at the home page and saw a few script samples.

My question is:

Am I hindering my clients by using javascript while being ignorant to JQuery and/or AngularJS?

答:
I think you should ask yourself if there is a reason you shouldn't stay up to date on current technologies in your field.  I think that is part of being a good software developer, and it allows you to make more informed decisions.

Choosing not to use a framework because it doesn't work for your situation is one thing, but staying ignorant to them, I think, is detrimental to you and your clients.


答:
It depends on whether or not you're writing a lot of bare Javascript code to perform functions that are already well-served (or perhaps better served) by the libraries.

In the specific case of jQuery, it is specifically designed to provide a library of useful functions in a cross-browser independent way.  So if you're writing a lot of hackish code to get around browser incompatibilities, jQuery can especially useful in that regard.

Libraries like AngularJS perform (among other things) a binding/templating function; that is, they allow you to bind data to your web page so that it is displayed in the page.  In addition, Angular provides support for several modern software patterns and a significant amount of sensible architecture.

What does this buy you?  Leverage, especially if you're writing even a moderately-sized web application.  Leverage means writing larger, more stable, more easily maintainable applications.

Title: Javascript, JQuery and now AngularJS What is happening?

Body:
I have been away from computers for about 3 years and starting to get back into programming. Lots has changed in resources and help sites available on the web especially the evolving StackExchange community. I come from the IRC #javascript, #html, #php days with php.net and a bit of google search finds here and there.

With that said, before I took my break from programming JQuery was around but not nearly as common as today. I personally stay away from it finding it easier to just write what I need done in traditional javascript.

Now I have just stumbled across AngularJS. I do not know much about it, just looked at the home page and saw a few script samples.

My question is:

Am I hindering my clients by using javascript while being ignorant to JQuery and/or AngularJS?


问:
Conception and design before coding: how much is this true?
I learned at school as well as I read everywhere else that a good development methodology needs conception and design before coding properly.

That is not a new information even for a beginner programmer. However, I wonder if this a good advice because since I started developing in several programming languages I never succeeded to design and conceive everything since the start.

I mean, I always melted design, conception and programming. Am I the worst developer in the world, or is the idea we learn at school just an old meaningless religious dogma?

How can we even conceive and design something we  never experienced and programmed before? Is not that ridiculous? Does not programming lead the conception and design instead?

答:
You absolutely must have some design before coding.

The reason is pretty straightforward - if you don't have any design, you don't know what you are making.

You absolutely must have some code before the design is final.

The reason is pretty straightforward - the design will change, and developing parts of the design will reveal questions, opportunities, and challenges that are hard to anticipate without starting to work on the solution.

Development is iterative.

Whether by plan or not, whether the team realizes it or not, every software project is done iteratively -- part of the work is completed, and then evaluated, and the evaluation leads to changes in how the rest of the work gets done.

Try more than one approach.

It takes practice and experience to know the best way to balance up-front design against creating code. It's a skill that almost no one has mastered and each project will have different ideals (consider designing a small tool for your own use versus a team creating a large, single-release product like a major video game).


答:
I think the answer has to be: Plan as much as you can, but not more than that.

Few people would speak against the virtues of planning, but the debate mostly overlooks an important aspect. Planning only works as far as you have the skill to make a good plan, that skill tend to come with experience. If you don't have a lot of experience any plan you draw up will likely have a fair amount problems, this means that in order to make a product that isn't a total disaster the plan will have to be revised heavily during development, if the plan is detailed then this will likely invalidate a lot of the details, or worse, you'll try to keep the adjustments to a minimum in order to be able to follow the plan.

Some things definitely require planning, and if you haven't got the skill for making the required level of plan, then the only way forward I can imagine is prototyping, writing code simply to gain the experience with the task required to make an adequate plan.

Whether or not you are ready to write production code, once you have reached your maximum level of planning there is nothing left to do but coding. Maybe it will be a disaster, but those are good learning experiences, and you will be much better equipped for making a revised plan.

Title: Conception and design before coding: how much is this true?

Body:
I learned at school as well as I read everywhere else that a good development methodology needs conception and design before coding properly.

That is not a new information even for a beginner programmer. However, I wonder if this a good advice because since I started developing in several programming languages I never succeeded to design and conceive everything since the start.

I mean, I always melted design, conception and programming. Am I the worst developer in the world, or is the idea we learn at school just an old meaningless religious dogma?

How can we even conceive and design something we  never experienced and programmed before? Is not that ridiculous? Does not programming lead the conception and design instead?


问:
Why are there no function pointers in Java?
Lately I started studying about different interesting concepts that exist in languages other than Java. Since the only language I've ever programmed with is Java, a lot of these concepts are very new to me. So this question may be very naive :) .

I learned recently about first class functions and function pointers. Why are there no function pointers in Java? Or at least some variation of them, like delegates in C#?

Maybe it's just the excitement of learning about this concept, but it seems to me like it could be a powerful feature in the language.

答:
Short answer: because Java has other ways to accomplish the same thing, and the language goes out of its way to hide pointers behind references which do not have pointer semantics.

Long answer:

The primary benefit of a function pointer in C or C++ is for an external library to plug in functionality at runtime, because a class is not known at compile time. Consider a WidgetFactory in an application. It is extensible: one may subclass it to produce new widget types. However, it is not possible for a C++ application to create a PluginWidgetFactory because it has not been written yet.

Enter function pointers: after loading a DLL/SO file dynamically, that library will call a function in the main application and register itself as a factory. It will provide a function pointer to say "call this function and I will return my subclass of WidgetFactory that your compiler knew nothing about."

In Java, you would use reflection. The Java WidgetFactory would check a system property with the class name, and load the PluginWidgetFactory dynamically using reflection.

While Java does not support function pointers, it can accomplish the same end goal using different mechanisms. The creators of Java felt these other ways were better due to their goal of hiding pointers.


答:
Function pointers by themselves are more or less a workaround for the lack of first-class functions. But Java does have first-class functions as of Java 8 (lambdas), and it had was of (somewhat) easily faking them since Java 1.1 (anonymous inner classes).

But actually, Java (or more precisely the JRE) also has a concept that more directly corresponds to function pointers than lambdas or anonymous inner classes: MethodHandles. It's a handle for a method. Which is really not much different than a pointer to a function. They were added in Java SE 7.

Body:
Lately I started studying about different interesting concepts that exist in languages other than Java. Since the only language I've ever programmed with is Java, a lot of these concepts are very new to me. So this question may be very naive :) .

I learned recently about first class functions and function pointers. Why are there no function pointers in Java? Or at least some variation of them, like delegates in C#?

Maybe it's just the excitement of learning about this concept, but it seems to me like it could be a powerful feature in the language.


问:
Help me catch up on what I've missed since Java 1.4.2
I am about to start my first professional career position as a software developer, and I'm likely going to be writing a lot of Java code.  I don't know that much about what specifically I'll be writing, and besides, I have fairly broad interests when it comes to code anyway.

For reasons not worth discussing, my last internship had me coding only for the Java 1.3 and 1.4 SDK's.  Also, my university education has focused mainly on algorithms, data structures, and other theory, not language features or libraries.

So, with the above in mind, what features, classes, etc. in the current version of Java (what number are we on now, anyway?) would be worth my time to read up on and why?  What have I missed since 1.4.2 that makes your life as a programmer easier?

Examples and stories of how you discovered a particular package or some such and put it to use would also be great.

答: Well, StringBuilder helped me to speed up my program. It is an equivalent of the StringBuffer without thread safety.

ContentLicense: CC BY-SA 2.5


问:
How can I get my team excited about writing a blog
My team has all agreed that writing a company development blog is a good idea. There are a lot of documented benefits to blogging, both for the individuals and the company.

However, while everyone agrees that a blog is a good idea in theory, no one seems to want to actually sit down and write an entry. Between having and endless flow of other work to be done, most of the team being introverts who don't generally like to put themselves out there, and the notion that there's a good chance the blog won't catch on and will be left to rot in some corner of the internet anyway, I'm not really sure how to get people excited about actually getting started. I don't want to just force someone to start writing if they don't want to, it doesn't help anyone to have a hastily written uninformative boring blog. What can I do to get my team excited about actually getting some article written?

答:
Start writing yourself.

Lead others by being an example for them. Since the team seems motivated, what blocks them is:

The fear of being the first one to write. The first entry will bring the attention of everyone within the team, and maybe outside of the team.

The fear of being completely wrong. What if they misunderstood the instructions, and they'll write a purely technical blog entry, while the blog is actually about puppies? Jokes aside, they may not know exactly what are the guidelines, the constraints, etc.

Hundreds of small details.

What is the advised length for each blog entry? Are entries with just a few paragraphs allowed? Would a blog post of twenty pages be perceived as boring?

What if the images are not working or the font they want to pick is available only in the WYSIWYG editor but not outside of it, and their blog post will appear ugly in production?

If you post something yourself, you simply solve all those constraints, and give some hints about what is expected from your coworkers.

Taking the first step is probably the most important factor which prevents people from doing something publicly.

There are still a few other issues to address:

Manage time.

[...] having and endless flow of other work to be done [...]

If your team is working on three products at the same time, all three being late for the last four months, indeed, your coworkers won't be inclined to write blog posts. In such case, there are also chances that higher management will perceive such time spending as a loss of time.

Ensure the team has enough time to discuss software-related topics together, learn things, teach them and write about them, and that management fully understands that a software development position doesn't consist in writing as much lines of code as one can.

Don't expose the information people want to keep private.

[...] most of the team being introverts who don't generally like to put themselves out there [...]

Most people won't write if it means that their first and family name will appear in the signature.

Ensure they have full control of the personal information which will be shown side by side with their posts. If they want to use a pseudonym, let them do it.

If they are introverts as in "I'm not talking to anybody all day long", there are serious communication issues inside your team which should be addressed first. I can hardly imagine somebody who barely talks to his coworkers starting a blog (unless he's just in a wrong team).

Popularity doesn't matter.

[...] and the notion that there's a good chance the blog won't catch on and will be left to rot in some corner of the internet anyway [...]

There are many reasons to write. One of them is being popular. Another one is to learn to write better. Another one is to be able to show to a potential employer that you know stuff by pointing to an article you've written on the subject.

All those reasons go away if there is a risk that the blog project will be abandoned by the company, and the blog will disappear in a few months. It's like working on a project for eight months, and then seeing the management cancelling this project one month before the official release date: all the time you spent on it is perceived as a waste of time.

Discuss clearly with your coworkers the aspects related to intellectual property, copyright, data safety, etc. It should be clear that the blog posts they write are theirs, and don't belong to the company. It should be clear that even if the blog doesn't hit 1000 visits per day in the next two months, it will still be online for the last ten years.

If you believe that the blog may become popular, be clear with your team: what makes you think so? How popular is your corporate website? How the blog would be discovered by readers and search engines? Would you use social network to promote the blog?

But it matters to know the audience.

Maybe popularity doesn't matter, but your coworkers still need to know who will read the blog posts.

Is it nobody, even other members of the team? In this case, motivation would be pretty low. They might want to write stuff in order to use it later when looking for a new job, but chances are, they will simply create their own blogs.

Is the boss reading the blog? What would be the reaction if somebody starts criticizing the company in this blog?

Are other developers from other teams reading the blog? If only the team is reading it, the style of the blog posts would be different, as well as the discussed topics.


答:
There's a fundamental incorrect assumption here. You will never be able to come up with a good design without writing code first (school will never teach you this). Yet, school is right that you won't get good code without design.

The solution is:

Write some code that you think might solve the problem.

Come up with a design based on what you learned from the code.

Throw away all the code and rewrite it from scratch according to the design.

Repeat as necessary.

Throwing away all the code is not an optional step in this process, but for small projects formally writing up the design may be. For large projects, you're more likely to repeat the "throw away all the code" step - though if you have sufficient modularity this may only apply to part of the codebase.

Far too many projects hold onto legacy code because they're unwilling to change it - or because it's too complicated, because it was never designed to be thrown away. Acknowledging the fact that your first attempt will be a failure will make your life much better.


问:
What are the common mistakes when you are a good coder in C and PHP and you start coding in Java ? What are good tips when switching?
What apsects of Java are the most diificult to learn when coming from such a background?  What common mistakes do people make ? What are the top timesaving and produtivtity increasing tricks ?

If you had a room of C/PHP coders who were about to start development using Java what advise would you give ?

This is my list of topics so far (in no particular order):

Use jodatime instead of the standard
library , and also less importantly
the guava library.

Arrays are zero indexed

I'd also highlight the
pass-by-value/reference aspects of
Java, and the fact that

```<code>String s1 = new String("test");
String s2 = new String("test");
if(s1 == s2) // will be false
if(s1.equals(s2)) // will be true
</code>```

Introduce the concept of design
patterns and give a quick overview.

Introduce Spring (it will be used) and the concept of
dependency injection

Is there anything obvious I am missing.

答: The automatic garbage collecting doesn't mean that you should give up memory usage optimization.


问:
Is there any point in writing a random tester for code that deals with inductive data structures?
Let's say we're writing a simple JSON parser and we've fully covered the code with unit tests:

it can parse primitives "0", "123", "-456", '""', '"asd"', true, false

it can parse arrays "[]", "[1, 2, 3]"

it can parse nested arrays "[[]]"

it can parse objects "{}", '{ "a": 1, "b": 2 }'

it can parse nested objects '{ "a": {} }'

Every possible JSON can be either a primitive or an array/object holding other primitives/arrays/objects - this is what I mean by inductive data structure (is 'recursive' a better term?). It seems to me that any JSON parsing can be reduced to these few cases and if the parser passes these tests then it is fully correct (unless it was explicitly hard-wired to break when you try to parse special numbers).

Is there still any point in creating a random tester that generates random stringified JSON in hope that one of them will break this parser? Would this random tester find anything interesting?

P.S. I chose JSON just as an example of an inductive data structure; I'm not interested in writing a JSON parser.

答:
(The terms 'recursive' and 'inductive' pretty much mean the same thing, mathematically speaking, although 'recursive' is more common among the computing crowd. Even more common for data structures is 'dynamic', which comes down to the same thing, since the possible shapes of dynamic data structures are invariably defined by conditions such as "...and you can nest another node just like this one at either end.")

You're right that a recursively defined parser that parses recursive input is unlikely to have bugs that require very complicated input to expose - ether the base case and the recursive case are handled right, or else they aren't. There is always the issue of resource limits, of course, but even that usually just requires very big input to check, not necessarily very complex input.

In my experience, the insidious defects in parsers occur through the combination of features that are, in themselves, well-supported: strings containing embedded quotes and embedded escape characters simultaneously, tokens that according to one standard are literals but in practice are often written with quotes anyway because present-day browsers expect it that way, etc. So you should be aiming for novel configurations to test, not so much for longer ones.


问:
Why is there no deterministic object destruction in Java?
I understand and enjoy the benefits of the Garbage Collection in Java. However I don't understand why there is no way in Java to explicitly (and quickly) destroy an object. Surely this could be useful in some cases, I assume performance-critical software.

It's true that in Java the GC will delete an object with no existing reference to it, so if I want an object deleted I can set the reference to it to null. But if I understand correctly, it isn't ensured that the GC will indeed delete the object, at least not immediately. And that's out of the programmer's control.

Why is there no way in Java to explicitly destroy objects?

While I understand that Java was designed to be used as a high-level language, that abstracts away some of the technical details from the programmer to make things easier: Java has become one of the most widely used languages, and is used in huge projects. I assume that in huge projects, performance is often an issue. Since Java had grown to become what it is, why wasn't explicit object destruction added to the language?

答:
Java makes auto cleanup:

As we all know Garbage collector do the clean up job automatically but WHEN? Every object is eligible for cleanup when it has no links.

```<code>Car c1=new Car();---Object 1
c1=new Car(); ---Object 2
</code>```

In line 2, Object 1 is eligible for garbage collection but this would be collected or not, it depends on many other factors. There are three heap spaces Eden, Survivor, Tenured Generation and JVM always wants a proper balance of memory(a proper saw tooth graph). Every object born in Eden space and follow other heap spaces according to it's age in program. So when any of these heap spaces fulls GC searches for objects with no links and make the cleanup for those object and shifts the remaining object to next heap space.

That's why in JDBC if we don't close Connections, Resultsets, Statements then there is a condition of OutOfMemory.

So JVM follow this type of cleanup management which it successful in most of the cases and there is no need of customized memory management. Even for preventing the cases like JDBC outofmemory problem java introduces try with resources, which frees the object at the end of try's scope.

```<code>try (BufferedReader br = new BufferedReader(new FileReader(path))) {
    return br.readLine();
  }
</code>```

Don't confuse with finalize() method it just calls before garbage collection invocation, it has no connection to customized memory clean like destructors in C++.

Body:
Java makes auto cleanup:

As we all know Garbage collector do the clean up job automatically but WHEN? Every object is eligible for cleanup when it has no links.

Car c1=new Car();---Object 1
c1=new Car(); ---Object 2

In line 2, Object 1 is eligible for garbage collection but this would be collected or not, it depends on many other factors. There are three heap spaces Eden, Survivor, Tenured Generation and JVM always wants a proper balance of memory(a proper saw tooth graph). Every object born in Eden space and follow other heap spaces according to it's age in program. So when any of these heap spaces fulls GC searches for objects with no links and make the cleanup for those object and shifts the remaining object to next heap space.

That's why in JDBC if we don't close Connections, Resultsets, Statements then there is a condition of OutOfMemory.

So JVM follow this type of cleanup management which it successful in most of the cases and there is no need of customized memory management. Even for preventing the cases like JDBC outofmemory problem java introduces try with resources, which frees the object at the end of try's scope.

try (BufferedReader br = new BufferedReader(new FileReader(path))) {
    return br.readLine();
  }

Don't confuse with finalize() method it just calls before garbage collection invocation, it has no connection to customized memory clean like destructors in C++.


答:
All six points you mention help the long-term robustness and reliability of the software during maintenance.

Other static analysis tools help in different ways.  Some examples:

SPARK tries to prove that no exceptions will ever be raised during execution.

GCC tries to detect uninitialised variables and dead branches.

Title: Checking program robustness using static code analysis

Body:
(Building on  this question)

If you have a static code analyser such as Checkstyle, is it possible to to relate any of the stuff that it checks for to actual robustness? Some of the things that Checkstyle checks for are e.g.:

Class design: Visibility of class members, enforcing public only static final members, no public constructors for utility classes, exceptions are immutable etc.

Coding: Inline conditionals, no empty statements, no illegal instantiation and magic numbers

Duplication: Checks for code duplication,

Import: Checks that packages are imported correctly

Metrics:  Checks everything from the number of times logical operators have been used in a statement to the number of classes that the given class relies on other classes (coupling) etc.

Naming Conventions: Checks many properties of variable name, package names, method names, class names etc

These are just some of the main things that Checkstyle checks for. Could any of these areas actually help "improve" the robustness of the code by detecting "errors" ? I mean sure it helps with the readability and other code smells, but I can't see how I can relate it to robustness.

Do you need to look at code in run-time to actually inspect robustness issues?


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

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

答:
I completed one of the developer bootcamps recently and can say with confidence that it helped me solidify the fundamentals of coding web apps in Rails and then some. The instructors also shoehorned in a couple JS frameworks (Backbone and Angular), SQL, basic BASH commands used in development and some cursory data structure knowledge.

Most of the students had no background in coding other than a handful of online tutorials in the weeks prior to class beginning. The apps we created were mostly CRUD, yes, though I'd say a number of students crafted some really excellent specimens. There's only so much we could do given the time frame.

However, what's happening now, in the aftermath, is that a number of us are realizing that employers don't know what to do with bootcamp graduates: we're better than plucking your average Joe or Jane off the street, but not yet production-ready. We're attending meetups and finding that there's great demand for "rockstar" engineers, or that "junior developer" means one or more years experience in a production environment.

Perhaps the market's saturated here (SF Bay Area) with entry-level developers, or something else dire is turning off hiring managers to picking us up -- I really can't say.

The bootcamps feel like they're doing their jobs well, though.


问:
What can I do to let our team have code reviews of branch merges having hundreds of screens worth of Github diffs?
"Code review" (aka "peer review") seems like a really great idea, so my team started practicing it.

For a little while it worked well, but then a co-worker merged a branch in, and asked for a review of the code.  When I went to review her code, the Github diff page was about 420k pixels in height.  Given that my screen is about 500px, that works out to 840 screens worth of code to review.

To read the code, fully "grok" it, and write appropriate comments, I probably need an average of one minute per screen, which works out to 14 hours.  Now to be fair, some libraries got checked in to this commit, so some portion of that can be skipped ... but even if libraries took up 6 hours worth, that still leaves me with an entire day spent reviewing this merge.

That can't be the most effective use of my time.  And this is just one merge; we will no doubt have other large merges to review in the future as well.

So, my question is, what can I do (either in terms of procedure or in terms of utilizing review tools) to let our team have code reviews of branch merges, while at the same time not eating up entire days on reviews?

答:
A working solution is to put a soft upper limit on how large merges you accept, but changes have to be reviewed as some point.

If you don't have much experience with source code reviews yet, you could start out recording metrics of the reviews (too):

Merge/commit size

Issues resolved

Errors introduced

Review reports

Reviewer

Time used

Volume of comments

Conclusion

...

These numbers will help you figure out what sizes of merges/commits are optimal in your organisation.

For your specific example, just committing the external library separately would have made the whole problem much, much smaller. - My basic assumption about merge/commit reviews is that the time it takes is proportional to the square of the size of the "diff" (I am at least certain that review time is not just linear, as you assume).  If you collect the metrics, you will be able to see how wrong my assumption is.


问:
Are short identifiers bad?
Are short identifiers bad? How does identifier length correlate with code comprehension? What other factors (besides code comprehension) might be of consideration when it comes to naming identifiers?

Just to try to keep the quality of the answers up, please note that there is some research on the subject already!

Edit

Curious that everyone either doesn't think length is relevant or tend to prefer larger identifiers, when both links I provided indicate large identifiers are harmful!

Broken Link

The link below pointed to a research on the subject, but it's now broken, I don't seem to have a copy of the paper with me, and I don't recall what it was. I'm leaving it here in case someone else figure it out.

http://evergreen.loyola.edu/chm/www/Papers/SCP2009.pdf

答:
I struggle...

I use to always use descriptive names as identifiers, but of late I've used very short identifiers.

I think, it depends on the context of the code:

If your writing complex functions (algorithms), then ALWAYS use short identifiers (single characters are best)

When writing Parameter values for functions use descriptive names.

I guess it depends on also how dense the code is. Sometimes having names actually makes it more difficult to read.

Sometimes without names its totally cryptic!

Title: Are short identifiers bad?


问:
Where to implement thread-safety logic for my queue data structure?
I will immediately confess that I do very little multithreading, so questions of style and organization in this domain a little fresh to me.

I've written a data structure (in Python, if that matters) which implements a special kind of a queue. I'd like to use this queue to pass messages between threads. Currently, the only logic I have has nothing to do with threads, and simply implements the "special sauce" of organizing messages in this queue.

I like having this queue as a data structure that has nothing to do with threads, just like any other data structure. However, I need to use mutexes, condition variables, etc. to implement the thread safety logic. The question is, where does this logic go?

Do I write a class, say, SpecialQueueConcurrent derived from SpecialQueue? Do I write a class that wraps SpecialQueue instead of deriving from it? Do I provide an option to make it concurrent in the constructor?

How is this usually done?

答:
It depends on the use-cases of the data structure, and any restrictions of that use you need to comply to (about that latter).

The use-cases

There are a few use cases that could determine the correct approach in choosing or implementing a concurrent data structure yourself. You need to consider:

The concurrency implementation supported by the structure:

Strict locking could guarantee supreme data consistency at the price of locks and can create performance bottlenecks.

Lock-free concurrent collections are special implementations that work without locks, but have (in most cases acceptable) possibility of one thread not reading the changes of the other. These are not the same as the case of using a standard collection without locks, as the lock-free collection would not allow the collection itself to become corrupted. With lock-free collections, the disadvantage is that multiple threads could perform the same operation, while only one of them would actually be taken into account. Depending on the context, this is often justified and acceptable, for these collections are introducing the best performance in concurrent processing, compared to lock usage, such repetitive processing situations are relatively rare to occur, and would usually not lead to corruption of the entire data/state.

Independent buckets that have their own locks is another approach that attempts to allow simultaneous use of the collection. In this approach the collection is internally split into multiple buckets with their own locks, that can be used by multiple threads. An example is a concurrent dictionary that would use internally an array of dictionaries. Based on the hash-code of the key the dictionary would decide which child dictionary to use from the corresponding thread, and will limit the lock to that child dictionary only. Another thread that would target another child dictionary will not be blocked. Alternatively, an array of lock objects can be used along a single container with quite the same effect. The problem with this approach is that the collection itself decides which bucket the current thread works on (and locks), so you do not have control of whether certain operations will really be concurrent (if manipulating by multiple buckets) or not (if they appear to affect the same bucket).

The number of threads dealing with a single instance of the structure simultaneously. This will determine the possibility of potential simultaneous uses that could cause blocking.

The ratio between read and write operations. This could help you decide which concurrent behavior from the listed above is suitable. For instance a collection that is more often being read from, than updated, would be more performant if it has a lock-free implementation, or if a read-write lock is used. The read-write lock is a special lock that allows you to control if it should block reads when a write is being performed, but to allow simultaneous reads.

The importance of data consistency within the structure. This is affected by the different approaches of such structure's implementation, as discussed above.

The restrictions

By restrictions I am referring to the code you are using. If you interact with a 3rd party API, or are somewhat restricted by the type of collection/structure you have to use (if you must pass it to the API's method), or you are enforced to implement certain interface, you need to find out the potential uses of this code and a suitable implementation that will fit. Most existing concurrent collection implementations would be compatible with at least the iterable and collection interfaces though.

Implementation notes

If you are going to base your structure on an existing collection, I recommend wrapping it, rather than using inheritance. Wrapping will guarantee you won't miss a method that needs to be synchronized, and will give you freedom to choose your locking behavior. You can always implement a standard collection interface in order to make your collection usable by other APIs (see restrictions section above)


问:
Is it appropriate to remove redundant code explicitly assigning the default values?
Sometimes while I'm editing something I see some useless code added by other developers, probably due to habit.

Editing this code will not make any difference, so is it appropriate?

In my specific case I'm talking about Java private fields like this:

```<code>private int aSimpleInt = 0;
private boolean myBool = false;
private MyObject obj = null;
</code>```

declaring the default values is redundant and useless.

Should I remove them or just skip?

答:
Declaring values that would already have been assigned by the compiler is useless for the behaviour of the program. However, that isn't what you should be optimizing as a professional developer. Instead, you should maintain your code base in the state that best supports ongoing development.

If code were only about its semantics here and now, you could think really hard once, slam out the necessary assembler code and never think about it again. But in the real world, requirement changes, fixes, maintenance, format changes etc. etc. keep coming one after another without end. It is crucial that your code base not only does what it's supposed to, but also remains in a state that lets you do the ongoing work that will be required.

Spelling out things that would already be the default can be helpful for that, so it's not automatically a bad idea. After all, you don't pay the compiler by the number of characters it consumes. You should declare things when doing so makes the code more readable.

In Java, global variables are automatically initialized, but local ones aren't; depending on the experience levels in your team (your current team and the expected future team!) it may be a good idea to spell things out so nobody ever has to think, even for a second, what value some variable will have at run-time, or it may not be. But "It doesn't change anything in the compiled program" is not a sufficient argument to call code "useless".


答:
The purpose of code is not so much communicating with the machine, but with fellow developers, so that a program can be maintained and effort is not wasted.  To me, redundant code is bad in the sense that it obscures the purpose of the program.  The compiler does not get tired to read lines, but a human reader does.

Let's consider a silly example:

int addTwo(int someNumber) {
    someNumber++;
    someNumber--;
    someNumber++;
    someNumber--;
    return someNumber + 2;
}
```

You could have n lines adding and subtracting from someNumber before you did the actual operation.  The hit on compilation time and performance is probably minimal.  However, if another developer has to scroll hundreds of lines (and in the worst case, think hard about them just to find out that they are useless), then you have wasted many minutes, and human effort.

So, my answer would be: remove redundant code and let readers focus on the purpose of your program.

Title: Is it appropriate to remove redundant code explicitly assigning the default values?

Body:
Sometimes while I'm editing something I see some useless code added by other developers, probably due to habit.

Editing this code will not make any difference, so is it appropriate?

In my specific case I'm talking about Java private fields like this:

```<code>private int aSimpleInt = 0;
private boolean myBool = false;
private MyObject obj = null;
</code>```

declaring the default values is redundant and useless.

Should I remove them or just skip?

Body:
The purpose of code is not so much communicating with the machine, but with fellow developers, so that a program can be maintained and effort is not wasted.  To me, redundant code is bad in the sense that it obscures the purpose of the program.  The compiler does not get tired to read lines, but a human reader does.

Let's consider a silly example:

int addTwo(int someNumber) {
    someNumber++;
    someNumber--;
    someNumber++;
    someNumber--;
    return someNumber + 2;
}

You could have n lines adding and subtracting from someNumber before you did the actual operation.  The hit on compilation time and performance is probably minimal.  However, if another developer has to scroll hundreds of lines (and in the worst case, think hard about them just to find out that they are useless), then you have wasted many minutes, and human effort.

So, my answer would be: remove redundant code and let readers focus on the purpose of your program.


问:
Should I follow the normal path or fail early?
From the Code Complete book comes the following quote:

"Put the normal case after the if rather than after the else"

Which means that exceptions/deviations from the standard path should be put in the else case.

But The Pragmatic Programmer teaches us to "crash early" (p. 120).

Which rule should I follow?

答:
In my opinion 'Guard Condition' is one of the best and easiest ways to make code readable. I really hate when I see if at the beginning of the method and don't see the else code because it is off the screen. I have to scroll down just to see throw new Exception.

Put the checks at the beginning so that the person reading code doesn't have to jump all over the method to read it but instead always scan it from top to bottom.


问:
Being a good mentee - a protégé
The complement of the Being a good mentor question.

I work with many very senior people that have vast amounts of knowledge and wisdom in Software, Engineering and our business domain.

What are some tips for gaining as much knowledge from them?  I don't want to take up too much of their time, but also want to take full advantage of this since it really could help develop my skills.

What are some good questions to get the conversation rolling in a sit down mentor/mentee session?  Some of the people providing mentorship have little experience in this area, so it would help to be able to lead some of these discussions.

答:
Tactics for engaging a senior developer in a discussion

Pick a time when they're not busy clacking away on the keyboard (coffee machine is good)

Don't be argumentative, you're not trying to disprove their approach, only to gain an overall understanding of what they consider important

Build up a rapport by referring to previous question and answer sessions so that they can see that you're developing as a developer

Ask their opinion on an approach you have taken with something, have it ready to show on your machine if they express an interest

Keep a pile of books on your desk (and refer to them) so they can see that you are readying around your subject, ask their opinion on those books and which ones you could benefit from reading

Above all, always be polite especially if you disagree with something.

Title: Being a good mentee - a protégé


答:
Quite often such things do have a function, in fact in Java in some situations it's required to do such an assignment.

Even if not explicitly required, for clarity it's often a good idea to do such an assignment, even if only for readability.

You should not generally change code unless there's a technical or functional reason, changes just because "it would look nicer otherwise" are not a good idea and all too often lead to bugs, especially if performed by people not intimately familiar with the system and/or language who can't predict all possible side effects of their changes.


问:
How to insert/update a large amount of data into mysql using php
I have an excel sheet which has a large amount of data. I am using php to insert the data into mysql server.

I have two problems

1) I have to update a row if the id already exists, else insert the data.

2) BIG PROBLEM : I have more than 40,000 rows and the time out on the sql server which is set by the admin is 60 seconds. When i run the update/insert query it will take more than 60 seconds, and because of this there will be a timeout. So the whole process will fail.

Is there a way I can do this ?

Currently I am checking the student id if it exists, then update otherwise insert. This I feel is taking a lot of time and causing the server to time out.

Also I have this field in the mysql stating the last time the data was updated(last_update). I was thinking of using this date, and if it is past a particular date(ie last time i ran the program) then only those rows should be updated.

Will this help in anyway ?

And what is the query i can run so as to check this date in the mysql database, that if it is past a particular date only those rows need to be updated and not everything else.
(Please help me with an example query for the above!!!!!!!!!!!!!!!!!)

答:
As suggested in this answer you can use INSERT...ON DUPLICATE KEY UPDATE method. But if you have large no of columns with heavy data then you need to prepare this query as batch statements and fire the query once it is prepare.

OR

You can create one single insert query per row and fire it. But this method is very expensive in terms of overall execution time of script and memory usage.


问:
Three variants of circular references between objects: how to choose?
I'm designing an object dependency graph of my program and one ambiguity between design variants appears from time to time.

Imagine two objects having a reference to each other. Obviously, at least one reference should be assigned after object's initialization (for example, through a subscription method) and another one optionally can be a direct dependency.

Here's an object diagram

I'm not sure I've used correct UML, so here's my description:

1) Both objects have subscription/binding methods. Usage:

```<code>A a = new A();
B b = new B();
a.Set(b);
b.Set(a);
</code>```

2) ObjectB is a component of ObjectA:

```<code>A a = new A(new B());

// somewhere, possibly in a's method :
b.Set(a);
</code>```

3) Third is actually an opposite of the second, no need to explain.

In my situation I can use any of these and my program will work, but I want some theoretical reasons. Can they be found?

答:
Disclaimer - I don't want to discuss if a cyclic reference is good or bad - IMHO there are situations where this kind of design is 100% appropriate, and for the sake of not starting a holy war, let's assume this is such a case here.

Your 3 alternatives don't differ much - at least, not in languages like C# or Java. What you get is two objects a and b, each holding a reference to each other. This is also true for (2) - if you see B as a component of A is more a question of your point of view (since classes are always reference types in these languages).

So the only difference between (2) and (1) is if you pass one of the two references within the constructor, or by using a separate Set method. Choose the "constructor" alternative if you want your cyclic references to be initialized immediately, after object construction, making sure they are as soon initialized as possible. Use the Set alternative if you need the option to delay the initialization (maybe you want to use single A objects without the need to provide always a B object - and vice versa - in some scenarios).

Final remark: it is much easier to make such a decision in terms of the context, knowing the names of the classes, the semantics, the context and the usage scenario.


问:
Adding field to the class at runtime - design pattern
Imagine your customer want's to have a possibility to add new property (e.g. color) to product in their eshop in their CMS.

Instead of having properties as fields:

```<code>class Car extends Product {
   protected String type;
   protected int seats;
}
</code>```

You would probably end up doing something like:

```<code>class Product {
   protected String productName;
   protected Map<String, Property> properties;
}

class Property {
   protected String name;
   protected String value;
}
</code>```

That is, creating own type system on top of existing one. It feels to me like this could be seen as creating domain specific langauge, or couldn't?

Is this approach a known design pattern? Would you solve the problem differently? I know there are languages where I can add a field in runtime, but what about database? Would you rather add/alter columns or used someting as shown above?

Thank you for your time :).

答:
Creating a type at runtime sounds much more complicated then just creating an abstraction layer. It is very common to create an abstraction to decouple systems.

Let me show an example from my practice. Moscow exchange has the trading core called Plaza2 with trader's API. Traders write their programs to work with financial data. The problem is that this data is very huge, complex, and highly exposed to changes. It can change after a new financial product introduced or rools of clearing changed. Nature of future changes can not be predicted. Literally, it can change every day and poor programmers should edit the code and release a new version, and angry traders should revise their systems.

Obvious decision is to hide all financial hell behind an abstraction. They've used well known SQL tables abstraction. Biggest part of their core can work with any valid schema, the same as trader's software can dynamically parse the schema and find out whether it is compatible with their system.

Returning back to your example, it is normal to create an abstract language in front of some logic. It could be "property", "table", "message", or even human language, but pay attention to the drawbacks of this approach:

More code for parsing and validating (and more time off course).
Everything what compiler did for you with static typing you must do
in the run-time.

More documentation of messages, tables or other primitives. All the
complexity goes from code to some sort of schema or standart. Here is
an example of above-mentioned financial hell schema:
http://ftp.moex.com/pub/FORTS/Plaza2/p2gate_en.pdf (dozens of pages of
tables)


答:
This is actually one of the benefits of introducing code reviews in your organization: getting people to make small, incremental changes.  Just wait until the guy that made that huge commit has to review a similarly sized commit of yours.

Other, more constructive ways of getting to the same result without starting a "commit war", could be:

setting a soft upper limit to merge sizes, as suggested by others

do not allow changes that break the limit by several orders of magnitude. Enforce breaking them into smaller chunks. Either this is possible, or the change is not well designed by its author.

do not check libraries into your repository, but handle them through a build system like maven or scons. This is such a general recommendation, that it makes me wonder if there is a special constraint in your team to check libraries in; in that case, I would suggest to you keeping them in a separate repository. If they are not your code, then you do not have to review them.

plan and reserve developer time to do code reviews. This should definitely count as development time. At first, the process will slow you down, but in a few months it will keep you moving at constant speed.

I would discourage trying to find tools that automate code reviews. This defeats the two main goals of the review: have a human review the meaning of a change that would escape a machine, and spread the knowledge about the code base among the developers.

Title: What can I do to let our team have code reviews of branch merges having hundreds of screens worth of Github diffs?

Body:
"Code review" (aka "peer review") seems like a really great idea, so my team started practicing it.

For a little while it worked well, but then a co-worker merged a branch in, and asked for a review of the code.  When I went to review her code, the Github diff page was about 420k pixels in height.  Given that my screen is about 500px, that works out to 840 screens worth of code to review.

To read the code, fully "grok" it, and write appropriate comments, I probably need an average of one minute per screen, which works out to 14 hours.  Now to be fair, some libraries got checked in to this commit, so some portion of that can be skipped ... but even if libraries took up 6 hours worth, that still leaves me with an entire day spent reviewing this merge.

That can't be the most effective use of my time.  And this is just one merge; we will no doubt have other large merges to review in the future as well.

So, my question is, what can I do (either in terms of procedure or in terms of utilizing review tools) to let our team have code reviews of branch merges, while at the same time not eating up entire days on reviews?


问:
How to not let anyone inspect elements of a webpage?
I was thinking to make some jQuery functions that will use ajax to control mysql. The whole idea is to make separate files of PHP (e.g query.php, addRow.php, update.php and delete.php) provide data to them via the GET variables like query.php?sql=SELECT * FROM table and then control them with jQuery AJAX functions that I'll make later. Expected code:

```<code>$(element).click(function (e) {
    mysql.query("DELETE row FROM table WHERE name = 'John Doe'");
});
</code>```

And then it'll send query through AJAX and the query will be performed.

So the problem is SECURITY . I mean anyone can just change javascript from browser's inspector or use console to control my databases. What can be done for this problem. Is there anyway to not let anyone change elements in the browser console. If not is there ANYWAY to overcome this security problem?

答:
I would suggest not to expose your database over the web this will have high risk on SQL Injection and data distortion.

Rather than to this you can create a separate data access layer which is a short of database functions which will interact with data base. Every time you need to include the required function file to your code and pass the connection object by reference to the function.

Also make sure function will not use $_SESSION register global at all.

Make separate database configuration file which contain database name, user name and password other relevant information. Now create connection object with use of those configuration details and pass the single connection object by reference to whatever query you fire.

Advantages of this.

This will reduce total no of database connection

reduce security risk because dbconfig.inc, dataretrive.fn.php and
other related file are kept in limited access directory which is
even not accessible by crawlers.

Site will use common database connection pool automatically.


答:
The biggest thing about Java compared with the languages you are talking about is the whole deal with Object Orientation. You can get by as a C or PHP programmer working almost entirely in a procedural way and if you want to be any good at Java you need to understand Object Orientation and understand it well.

If you can make sure they have learned that, not only will it make them better Java programmers, but it will be useful to them with any other languages they learn in future.

Title: What are the common mistakes when you are a good coder in C and PHP and you start coding in Java ? What are good tips when switching?

Body:
What apsects of Java are the most diificult to learn when coming from such a background?  What common mistakes do people make ? What are the top timesaving and produtivtity increasing tricks ?

If you had a room of C/PHP coders who were about to start development using Java what advise would you give ?

This is my list of topics so far (in no particular order):

Use jodatime instead of the standard
library , and also less importantly
the guava library.

Arrays are zero indexed

I'd also highlight the
pass-by-value/reference aspects of
Java, and the fact that

```<code>String s1 = new String("test");
String s2 = new String("test");
if(s1 == s2) // will be false
if(s1.equals(s2)) // will be true
</code>```

Introduce the concept of design
patterns and give a quick overview.

Introduce Spring (it will be used) and the concept of
dependency injection

Is there anything obvious I am missing.


问:
Determine Cluster Label in K-means
I have dataset that is contain 150 data that is actually divided into 3 group. Each group has it’s own label.

I do clustering process with K-means algorithm to group the data.

I need to assign the label of each group that is created by K-means process. So I could compare the result of K-means with the data training.

Anybody could help to explain how to determine the label of each group?

答:
arbitrarily choose the label for each group and check the result with each of the 3! permutations

or if the label relate to the relative location you can use that, N is assigned to the group with the highest y coordinate and so on

Title: Determine Cluster Label in K-means


问:
Large MySQL Batch Inserts From PHP: Run insert from script, or save as SQL file?
We have a large dataset that's current residing in many, many spreadsheets.

I've been tasked with getting part of that data into our MySQL DB.

When all is said and done, I will probably be inserting somewhere around 3 million rows.

I intend to collect the inserts into batches of about a quarter-million or so (parsing through it with PHP).

Initially, my plan was to just run/send those batch INSERTs straight from my script.

More recently, though, I thought about actually writing out the INSERTs to .sql files for later importing.

I tried to google around on this a little ... didn't find much.

Are there any real pro's/con's one way or the other?

If not, I'm inclined to stick with my original plan.

Otherwise, I'm completely open to suggestions.

答:
I think importing millions of records through the php script is not a good idea. What you can do is, prepare multiple .sql files with bunch of records based on the setting of execution time and memory of your server. and put it in one fixed location directory also .sql file name with some logical sequence so that we can read the file programmatically.

Write small shell script which extract each file entry in that particular directory. In terms of UNIX/LINUX you need to write shell script. If it is windows server you need to write batch file.

and within that batch file write following command.

mysql -u userName -p password databaseName < FileName.sql > logfile.log

Now lets assume that I had created 10 sql file. so I named as 1.sql, 2.sql and so on and access those in loop using shell script/batch file.


问:
Managing client-side and server-side validations in one place
I'm 100% on board with the case that one should definitely use both client-side and server-side data validations.

However, in the frameworks and environments I've worked in, the approaches I've seen have never been DRY. Most of the time there's no plan or pattern - validations are written in the model spec, and validations are written in the form on the view. (Note: Most of my first-hand experience is with Rails, Sinatra, and PHP w/ jQuery)

Mulling it over, it seems like it would not be difficult to create a generator which, given a set of validations (e.g. model name, field(s), condition), could produce both the necessary client-side and server-side material. Alternately, such a tool could take the server-side validations (such as the validates code in an ActiveRecord model) and generate client-side validations (such as jQuery plugins, which would then be applied to the form.

Obviously, the above is just a "hey I had this idea" musing, and not a formal proposal. This sort of thing is surely more difficult than it seemed when the idea hit me.

That brings me to the question: How would you approach designing a "write once, run on server and client" technique for data validation?

Related subtopics: Do tools like that exist for any particular frameworks or client-server technologies? What are major gotchas or challenges with trying to maintain only one set of validations?

答:
I was just thinking about the same problem. I was thinking of using ANTLR to get an abstract syntax tree in both C# and javascript. From there you use tree walkers to apply the actions specified in the language to the objects to be validated.

So then you could store a description of the required validation where ever you like - possibly in the database.

This is how I would approach the problem.


答:
This kind of condition ordering depends on the criticallity of the code section under question
and whether there are defaults that can be used.

In other words:

A. critical section and no defaults => Fail Early

B. non-critical section and defaults => Use defaults in else part

C. in-between cases => decide per case as needed

Title: Should I follow the normal path or fail early?

Body:
From the Code Complete book comes the following quote:

"Put the normal case after the if rather than after the else"

Which means that exceptions/deviations from the standard path should be put in the else case.

But The Pragmatic Programmer teaches us to "crash early" (p. 120).

Which rule should I follow?


问:
How to hide AOP implementation dependency without breaking encapsulation?
I have the concept of a SlowLoading thing:

```<code>public interface SlowLoading {
  boolean hasLoaded();
}
</code>```

I also have a component MyComponent:

```<code>public interface myComponent{
  void doSomething();
}
</code>```

My implementation covers both:

```<code>public class MyComponentImpl implements SlowLoading, MyComponent {
   // omitted for brevity
}
</code>```

I have a container (interface omitted for brevity) which returns MyComponent:

```<code>public class MyContainerImpl implements MyContainer{
  @Inject private MyComponent component;

  @Override
  public MyComponent doSomething(){
    // magic happens
    return myComponent;
  }
}
</code>```

I also have an AOP component that intercepts the return of slow loading things and implicitly waits for them to load before returning:

```<code>@Pointcut("execution(SlowLoading+ *(..) )")
  public void returnsSlowLoadingThing() {
}
</code>```

However, at present the MyContainer method is not proxied, since the return value does not implement SlowLoading.

What is the best way to encapsulate this behaviour?

Options I've considered:

Make MyComponent extend SlowLoading.  This feels like a code smell and breaking of encapsulation - bleeding implementation into the interface.  A client does not care if it is slow loading or not.

Inject MyComponentImpl directly into my container and return it explicitly (co-variant returns).  Again, this feels like it is breaking encapsulation and the point of programming to interfaces, but feels better than the above, since it is done at a lower level and hidden behind the interface (implementation detail).  However it is breaking the encapsulation of the AOP functionality which should be orthogonal and transparent.

Perform the AOP wait before invoking a method on a SlowLoading thing.  This seems the most appropriate, but I've not been able to get this working so far.

答:
i think this is not the best example for AOP.

It seems it would have to break encapsulation, possible workarounds may be:

A. Use 2 more interfaces that cover the 2 cases of SlowLoading (either wait or not-wait) and use one of these interfaces in the AOP cut

B. Not use AOP at all for this functionality and use 2 interfaces (as above) that handle different cases of SlowLoading (wait and block or not-wait and proxy). This would also make use of some factory pattern to get the correct SlowLoading instance (either wait or non-block)

OwnerDisplayName: Tim


答:
Read up on cluster evaluation in Wikipedia.

No clustering algorithm will assign a label such as iris_setosa to the cluster, unless you provide the labels to the clustering algorithm somehow (but then it is no longer clustering, actually, but classification).

So you will only have first_cluster, second_cluster, third_cluster type of labels.

There are various measures proposed to compare the structure of the clusters in comparison to the original data set. But usually there will not be a 1:1 correspondence to the original labels.

Title: Determine Cluster Label in K-means

Body:
I have dataset that is contain 150 data that is actually divided into 3 group. Each group has it’s own label.

I do clustering process with K-means algorithm to group the data.

I need to assign the label of each group that is created by K-means process. So I could compare the result of K-means with the data training.

Anybody could help to explain how to determine the label of each group?


答:
As always, asking a question advances my own understanding of the issue.

The main difference between those three variants is object's lifetime. That what is absent when we are talking about classes, but it is very important in case of objects.

In first variant, lifetimes are independent. Both objects can live without each other. a's knowledge of b starts from receiving a message about it, the same as b's knowledge of a. The responsibility for connecting those object's lifetimes falls to a third object, so this variant must be used only when there is a real need to have a and b living without each other. That is rare, actually. I'm still searching for a good and simple example.

In the second variant a knows about b during all life. We say a owns b and use something like C#'s readonly modifier for a field with reference to b. But b can't own a, because it will be impossible to instantiate them. In other words, direct component graphs can't have cycles. Instead, we can use a's right to configure it's own components, to inroduce itself to b. In this case we don't need third object to connect these two, but we must complicate a's state with additional field like isInitialized which must be checked each time we use a.

Title: Three variants of circular references between objects: how to choose?

Body:
I'm designing an object dependency graph of my program and one ambiguity between design variants appears from time to time.

Imagine two objects having a reference to each other. Obviously, at least one reference should be assigned after object's initialization (for example, through a subscription method) and another one optionally can be a direct dependency.

Here's an object diagram

I'm not sure I've used correct UML, so here's my description:

1) Both objects have subscription/binding methods. Usage:

```<code>A a = new A();
B b = new B();
a.Set(b);
b.Set(a);
</code>```

2) ObjectB is a component of ObjectA:

```<code>A a = new A(new B());

// somewhere, possibly in a's method :
b.Set(a);
</code>```

3) Third is actually an opposite of the second, no need to explain.

In my situation I can use any of these and my program will work, but I want some theoretical reasons. Can they be found?


问:
How do I get into R&D?
I'm beginning to think that I might be best suited for a job in R&D.  The reason being that I like jobs that allow me to be creative and I generally am more interested in solving puzzles than building things.  I really dislike jobs that just boil down to translating requirements into code.

Here's the kicker though:  I don't have a bachelor's much less a masters or phd.  Is it possible for me to land a job like this?

答:
Your best shot it to get at least a masters degree.  You may get lucky, but most interesting R&D positions require smart people and a higher degree is like a "smart persons badge" to a typical HR person.

You learn lots of interesting things doing a good Uni degree that are hard to pick up in a boring coding job.  And you will start learn how to do the R part of R&D.

From there you can decide whether you are better suited to academia or industry.  A PhD is pretty much essential for an academic career, and is also useful if you want to land an R&D position with a top rank IT company like Google, IBM, Microsoft, Oracle and so on.

Title: How do I get into R&D?


答:
Sometimes you can't get away with a small change. You might need to forgo GitHub's code review tools and use Plain Old Git:

```<code>$ git remote add somebody https://github.com/somebody/repo.git
$ git fetch somebody
$ git diff --name-only development somebody/topic_branch
# shows list of files that were touched
$ git diff --name-status development somebody/topic_branch
# Shows list of files plus whether they were added, deleted, modifed, renamed, etc.
</code>```

Then you can use:

```<code>$ git difftool development somebody/topic_branch -- ./path/to/file/or/directory
</code>```

This will help you whittle down the diff.

Or just see the diffs of all non added files:

```<code>$ git diff --name-status development somebody/topic_branch | grep -vE '^A'
</code>```

If you have a comment to make, you can always head back to GitHub and comment on the file or line once you've had a chance to review things.

Body:
Sometimes you can't get away with a small change. You might need to forgo GitHub's code review tools and use Plain Old Git:

$ git remote add somebody https://github.com/somebody/repo.git
$ git fetch somebody
$ git diff --name-only development somebody/topic_branch
# shows list of files that were touched
$ git diff --name-status development somebody/topic_branch
# Shows list of files plus whether they were added, deleted, modifed, renamed, etc.

Then you can use:

$ git difftool development somebody/topic_branch -- ./path/to/file/or/directory

This will help you whittle down the diff.

Or just see the diffs of all non added files:

$ git diff --name-status development somebody/topic_branch | grep -vE '^A'

If you have a comment to make, you can always head back to GitHub and comment on the file or line once you've had a chance to review things.


问:
What's the copyright status of boilerplate code?
I check Open Source Compliance for commercial code.

I have recently found a few examples where the commercial source is matched against quite a few OSS projects. The matches are very similar, but not exact, say about 30 lines of code with about 4 methods, a few variables names differ, some extra lines in the commercial code, ... but substantially the same. I don't think this is auto-generated code, nor copy-pasta, because things like comments will differ.

Rather it just looks like boilerplate - the developers say that Grails (and these examples always seem to come up in Grails, but it could be any framework) requires a specific script format for CRUD operations (and these examples are also predominantly CRUD operations). If one adds in a standard source-code style, then it amounts to boilerplate - even if it is original it's going to end up as very similar looking across a number of codebases.

Which leaves me with 2 questions:

Is this a reasonable defence against accusations of copyright infringement?

How would one form a judgement that codeX is such boilerplate, but codeY is not (as a non-expert in the language+framework)?

答:
Disclaimer: I am not a lawyer.

This is part of the idea/expression divide. The short form is that ideas cannot be copyrighted, only their expression can. And if the idea has only one (or a small number of) expressions, those expressions can't be copyrighted.

Whether or not this can be used as an infringement defense depends on jurisdiction and/or legal precedents.


问:
How exactly to use the MVC design pattern
I have read the documentation on the apple's developer website which refer following guidelines

A view class shouldn't depend on a model class (although this may be unavoidable with some custom views).

A view class shouldn't have to depend on a mediating controller class.

A model class shouldn't depend on anything other than other model classes.

A mediating controller class shouldn’t depend on a model class (although, like views, this may be necessary if it's a custom controller class).

A mediating controller class shouldn't depend on view classes or on coordinating controller classes.

A coordinating controller class depends on classes of all MVC role types.

Consider this scenario:

I have a view controller class called EmployeeViewController.
I have some minor components of which are some are programmatically created and some are created through xib.

What exactly I am doing is creating all the subviews inside the EmployeeViewController class and adding them to the EmployeeViewController's view, e.g. [self.view addSubView:…]

Is it a better option for me to create a seperate UIView Subclass which consists of all the components and initialize it once and add it in the EmployeeViewController?

What exactly is the correct way to implement MVC? Am I supposed to create separate components for view and controller or should I stack subviews inside the EmployeeViewController?

答:
The question you ask is not so much about how to use MVC in general, but how to manage/implement the specific composite views you need.

So having the basics and purpose of MVC design pattern in place, the answer might take multiple paths:

A. use a dependency injection pattern in the main view ie. EmployeeViewController's view to add/inject any sub-views it might need

B. depending on the which view/class is responsible for the data/model the main view itself can generate the sub-views and initialize them

C. not use sub-views at all but re-structure the main view to handle the data by itself in one view


答:
One way would be to use same language / framework on both server and client side.

E.g.

Node.js :: Client / Server in JavaScript
GET :: Client / Server in Java

In this case, most of the "Domain Object" code would be common, that would include validation.
Framework will invoke the code as required. E.g. Same code would be invoked in browser before "submit" and on server side web service.

EDIT (June/2014) : With Java 8, is now easy to integrate JS validation code in Java Applications as well. Java 8 has a new JS execution engine that is more permanent (E.g: it makes use of invokeDynamic).

Title: Managing client-side and server-side validations in one place

Body:
I'm 100% on board with the case that one should definitely use both client-side and server-side data validations.

However, in the frameworks and environments I've worked in, the approaches I've seen have never been DRY. Most of the time there's no plan or pattern - validations are written in the model spec, and validations are written in the form on the view. (Note: Most of my first-hand experience is with Rails, Sinatra, and PHP w/ jQuery)

Mulling it over, it seems like it would not be difficult to create a generator which, given a set of validations (e.g. model name, field(s), condition), could produce both the necessary client-side and server-side material. Alternately, such a tool could take the server-side validations (such as the validates code in an ActiveRecord model) and generate client-side validations (such as jQuery plugins, which would then be applied to the form.

Obviously, the above is just a "hey I had this idea" musing, and not a formal proposal. This sort of thing is surely more difficult than it seemed when the idea hit me.

That brings me to the question: How would you approach designing a "write once, run on server and client" technique for data validation?

Related subtopics: Do tools like that exist for any particular frameworks or client-server technologies? What are major gotchas or challenges with trying to maintain only one set of validations?


问:
Why are strong names optional?
Why the c# allows project not to be strongly signed when they are build? They may be signed by some automatic name file if programmer do not choose his(hers) own sign file. Where is the advantage of not signed .dll file?

What the strong names are?

I am working on project which uses C# .dll files in Microsoft Dynamics AX. If the .dll file has the strong name it is easy to use. If not the fun begin.

If the .dll do not have strong name

You can not easy install it to gacutil

You can not use it as a reference when you build a project with strong name.

It can leads to DLL Hell

I see only disadvantages of project without strong names so I want to know if I miss see something or there is some tricky historical consequences why they are still allowed. I want to know if there is some advantage of using them.

It should be possible to add  strong name to .dll file without compiling but I was not able to use this because I end after I try to use ILASM.exe with "The program can't start because fusion.dll is missing from your computer, Try reinstalling the program to fix this problem." even if the fusion.dll is in the system (We decided to use different approach so I don't have time for more tries on this solution.)

答:
Some reasons NOT to sign an assembly:

Because signed assembly can only load other signed assemblies. - a real problem if you rely on 3d party libs.

When project is signed it's requires to have the versions, so  you can't use direct bindings between your projects in the same solution or you'll have to recompile the application to be able to use a different version.

Apart from the obvious inconvenience, there's also some performance issues (not significant though) because of verification of the signature. (If you interested to know the performance issue in depth , read here strong name by Richard Grimes

P.S. C#: why sign an assembly?

ContentLicense: CC BY-SA 4.0

Title: Why are strong names optional?


问:
When is a script no longer a script?
I write many a PowerShell script for the organization I currently work for. Most recently I have been co-writing a tool that, in the end, will have a lot of functionality (beyond a single purpose), will be configurable, and will have both a CLI and GUI, all in PowerShell. So when does a script stop being a script and when can you call it an application or a program. Is this just kind of in the eye of the beholder?</p>

答: There are no hard lines drawn in the sand for this. It often comes down to who is doing the work and how comfortable they are with non scripting languages and what level of rigor you have on scripts vs application. People writing scripts are generally not considered (generally) full blown developers that use source control, various design patterns, unit testing, etc. Scripts were generally created to avoid all that rigor and do a task fast. Developers will often still insist that scripts at least still be in source control but the places I've worked this rarely happens because generally it's not "developers" writing them and so control is minimal around them. It's people who want something done and know enough to be dangerous.

Title: When is a script no longer a script?


问:
HTTP Session: A single object or multiple?
I tested two approaches to store session data:

The classic: 1 key, 1 object (And every key as static final String in a class)

"user" --> UserObject

"preferences" --> List

...

An approach with only 1 object

"sessionObject" --> SessionObject

And my SessionObject contains UserObject and the list of preferences as attributes. This is a fairly simple example but imagine it with 20+ attributes.

The advantage I see in the second approach is that :

You only have to delete one key to ensure session is empty

You don't have to create the bothersome set of final static String to create the keys

You'll know what type of object to retrieve (Using key you have to cast)

Do you see any problem I might went over? Or does anything go against best practices?

答:
For those having the same question :
In Application Servers like Weblogic when doing clustering and session replication. The session is copied to other servers when its modified.
To trigger this copy, it seems that the server checks the references of the objects in the session and once it detects a change replication is done.
So using only one object containing other may prevent the copy to be triggered.

Not tested.


问:
Dataset with coordinates of borders of countries
I am creating an application that visually displays world regions, e.g. to place markers within an administrative region.

Does a dataset exist with geometrical or geographical (long/lat) descriptions of the world's current country borders (and possibly other administrative divisions)?  Ideally the dataset would be in a format that I could easily generate border images of the size that I require.

答:
Just earned the "popular question" bagde for this question. Therefore, maybe for someone helps the next.

I'm currently using free 1:110 mil. shapefiles from http://www.naturalearthdata.com.

From their site:

Natural Earth was built through a collaboration of many volunteers and
  is supported by NACIS (North American Cartographic Information
  Society), and is free for use in any type of project (see our Terms of
  Use page for more information).

For my needs (drawing an simple word map with an perl script) it is the simplest possible way.


答:
A "script" is a set of instructions that do something the user could do themselves, only faster and with less possibility for error.

Sure, I could delete all my old log files manually, but the script Bob wrote does it just fine.

An "application" or "program", in contrast, is an automated or interactive bit of software that can be thought of as doing things "on its own", rather that work the user would do themselves.

Help Desk asked me to run the "Log Import" program, so it send them the relevant data.

The difference really is one of degree and issue, and there are lots of programs that do things the user could do themselves, and some scripts that do things users cannot do directly.

If you have the draw the line somewhere formally, draw it at "would your end-user do this manually if this thing wasn't here?"

Title: When is a script no longer a script?

Body: I write many a PowerShell script for the organization I currently work for. Most recently I have been co-writing a tool that, in the end, will have a lot of functionality (beyond a single purpose), will be configurable, and will have both a CLI and GUI, all in PowerShell. So when does a script stop being a script and when can you call it an application or a program. Is this just kind of in the eye of the beholder?</p>


问:
Help me catch up on what I've missed since Java 1.4.2
I am about to start my first professional career position as a software developer, and I'm likely going to be writing a lot of Java code.  I don't know that much about what specifically I'll be writing, and besides, I have fairly broad interests when it comes to code anyway.

For reasons not worth discussing, my last internship had me coding only for the Java 1.3 and 1.4 SDK's.  Also, my university education has focused mainly on algorithms, data structures, and other theory, not language features or libraries.

So, with the above in mind, what features, classes, etc. in the current version of Java (what number are we on now, anyway?) would be worth my time to read up on and why?  What have I missed since 1.4.2 that makes your life as a programmer easier?

Examples and stories of how you discovered a particular package or some such and put it to use would also be great.

答:
Wow that was a blast from the past! I've not used Java for 4 years now - and nothing has changed at all in that time!

There's a list of features by version, but here's the important bit (plagiarised of course)...

J2SE 5.0 (September 30, 2004)

Generics: Provides compile-time (static) type safety for collections and eliminates the need for most typecasts (type conversion).

Metadata: Also called annotations; allows language constructs such as classes and methods to be tagged with additional data, which can then be processed by metadata-aware utilities.

Autoboxing/unboxing: Automatic conversions between primitive types (such as int) and primitive wrapper classes (such as Integer).

Enumerations: The enum keyword creates a typesafe, ordered list of values (such as Day.MONDAY, Day.TUESDAY, etc.). Previously this could only be achieved by non-typesafe constant integers or manually constructed classes (typesafe enum pattern).

Swing: New skinnable look and feel, called synth.

Varargs: The last parameter of a method can now be declared using a type name followed by three dots (e.g. void drawtext(String... lines)). In the calling code any number of parameters of that type can be used and they are then placed in an array to be passed to the method, or alternatively the calling code can pass an array of that type.

Enhanced for each loop: The for loop syntax is extended with special syntax for iterating over each member of either an array or any Iterable, such as the standard Collection classes, using a construct of the form:

Java SE 6 (December 11, 2006)

Support for older Win9x versions dropped. Unofficially Java 6 Update 7 is the last release of Java shown to work on these versions of Windows. This is believed to be due to the major changes in Update 10.

Scripting Language Support: Generic API for tight integration with scripting languages, and built-in Mozilla JavaScript Rhino integration

Dramatic performance improvements for the core platform, and Swing.

Improved Web Service support through JAX-WS

JDBC 4.0 support.

Java Compiler API an API allowing a Java program to select and invoke a Java Compiler programmatically.

Upgrade of JAXB to version 2.0: Including integration of a StAX parser.

Support for pluggable annotations

Many GUI improvements, such as integration of SwingWorker in the API, table sorting and filtering, and true Swing double-buffering (eliminating the gray-area effect).

JVM improvements include: synchronization and compiler performance optimizations, new algorithms and upgrades to existing garbage collection algorithms, and application start-up performance.

That's about it. Java SE 7.0 looks more interesting but isn't released yet.

Considering how many new language features and APIs have been added to C# in the last 4 years, I'm quite astonished. What's been going on at Sun/Oracle?


答:
As others have said, the answer isn't really clear cut. The way I see it, a script requires little to no user interaction once it is being run. Scripts are less flexible in that sense. An application or a program would be more robust, allowing for more user interaction while it is in the process of running. What you are writing seems like more of a program than a script to me, since it sounds like there will be quite a bit of user interface.

From my own experience, a script is something you would just provide some parameters to and run. It would be completely or nearly completely automated. On the other hand, if the user is continually being prompted, or having to provide input while the code is being run, that is a bit more robust and less automated. Scripts are more about automation vs. a program which is more robust with user interaction. As an example, a script can be something concatenating a list of txt files into one txt file. A program would would allow the user to continually choose files to concatenate during run time.

Title: When is a script no longer a script?


问:
URI Representing a Single Resource with Two Possible Identifiers
I have a resource that can be represented in one of two ways:

Big Serial Number, or

Small Serial Number

Is it closer adherence to REST principles to:

A: have a query string specify the type (https://acme.org/api/widget/aaa-111-aaa?type=big vs https://acme.org/api/widget/aaa?type=small), or

B: have query strings specify the type as search parameters (https://acme.org/api/widget?serial=aaa-111-aaa?type=big vs https://acme.org/api/widget?serial=aaa?type=small), or

C: in the URI (https://acme.org/api/widget/big/aaa-111-aaa vs https://acme.org/api/widget/small/aaa), or

D: something else (ex: headers)?

To me, it seems like having it in the URI (option C) specifies an entirely different resource, and in this case, they should represent the exact same resource. Is option A the best way to represent this?

答:
How you decide to structure your URI is not essential to REST, which is an interaction model.  If you work with web servers, and you work on a per-request basis instead of a conversation basis, you're already in the RESTful way of working.

I'm not aware of an accepted consensus on what shape of URI is preferable, and it may be a matter of opinion.  I prefer C because I see the URI path as the 'solid' part of a URI, and the query parameters as a 'temporal', per-query modification, such as requesting it in JSON instead of XML.  But ultimately, that's just my opinion.  At any rate, there is no rule against having multiple URIs for the same information, so C is no less viable than the others.

StackOverflow has an interesting question and insightful answers on this: REST API Best practices: Where to put parameters?

As for your IDs, I'm going to look at this problem through the lens of a hypothetical user/consumer of your URIs, which brings me to two considerations:

Are your ID types syntactically distinguishable?  As in, if I just give you a string, can you tell with 100% certainty which type it is?  If yes, don't distinguish between short and long; accept them both interchangeably.

```<code>acme.org/widget/aaa-111-aaa
acme.org/widget/aaa
</code>```

Does the small number need more info?  A category, maybe?  Then you have two different paths already, and you don't need to worry about the rest (no pun intended):

```<code>acme.org/widget/aaa-111-aaa
acme.org/widget/dynamite/aaa
</code>```

Body:
How you decide to structure your URI is not essential to REST, which is an interaction model.  If you work with web servers, and you work on a per-request basis instead of a conversation basis, you're already in the RESTful way of working.

I'm not aware of an accepted consensus on what shape of URI is preferable, and it may be a matter of opinion.  I prefer C because I see the URI path as the 'solid' part of a URI, and the query parameters as a 'temporal', per-query modification, such as requesting it in JSON instead of XML.  But ultimately, that's just my opinion.  At any rate, there is no rule against having multiple URIs for the same information, so C is no less viable than the others.

StackOverflow has an interesting question and insightful answers on this: REST API Best practices: Where to put parameters?

As for your IDs, I'm going to look at this problem through the lens of a hypothetical user/consumer of your URIs, which brings me to two considerations:

Are your ID types syntactically distinguishable?  As in, if I just give you a string, can you tell with 100% certainty which type it is?  If yes, don't distinguish between short and long; accept them both interchangeably.

acme.org/widget/aaa-111-aaa
acme.org/widget/aaa

Does the small number need more info?  A category, maybe?  Then you have two different paths already, and you don't need to worry about the rest (no pun intended):

acme.org/widget/aaa-111-aaa
acme.org/widget/dynamite/aaa