问:
A measure of development speed
I've seen a lot of tests measuring execution speed of programming languages, but I've never found tests measuring development speed.

I've heard development speed is increased when working with dynamic languages, but is there any proof of that ? I'm not trying to say dynamic languages aren't efficient, but I'd kind of like to see the results of a scientific study, if such a thing exists.

Even better would be informations on maintenance facility. Are some languages easier to debug than others ?

EDIT : I'm mostly interested in the differences between two languages that are close in syntax. For example, I guess programming in C will usually be slower than programming in Java; but is programming in Java faster than programming in C# ?

答:
I'm not sure this is relevant, but it is interesting

In The Mythical Man Month, Fred Brooks mentions studies comparing assembly and higher level languages. They found that programmers produced the same amount of instructions per year in both, but the instructions for a high level language were equal to multiple assembly language instructions. So by switching to the high level language, the programmers achieved an increase whatever the average multiple of assembly instruction to language instruction in productivity.

The same should be true of C vs Java/C#, I don't know the real difference between C# and Java. But every time you increase the level of abstraction, you will increase productivity. However I also think that it will reduce control over what the machine is actually doing. You have to trust that the language is doing what you want. For instance in high performance software, garbage collection is unacceptable, except if you have complete control over when it is run, and how long it runs for.

Title: A measure of development speed


问:
Fiction that includes BASIC programs
Back in what must've been the mid-80s, when every microcomputer included BASIC and Choose Your Own Adventure Books were really popular, there were some novels that had BASIC programs listed in the text, for you to type in and further enjoy.

For example, as I recall, in one of these books, the adventurers were infiltrating an undersea base (and eventually wiped the bad guy's data storage [I do believe it was a hard drive, even though they were uncommon then]).  One of the programs involved a game were you piloted a submarine and had to avoid or shoot sharks.  The code was in BASIC; minor changes (such as 'CLS' -> 'HOME') had to be made for your specific computer, and it used good old 40-column text-mode to display the action.  IIRC, the plot never depended upon the programs.

My question is, does anyone else recall these sorts of books?  Do you know any titles that I could look for, or of any online?  I am toying with the idea of writing a story like this (no, not in BASIC!), and would really like to see how it was done, back in the day.

答:
Wikipedia has a long list of books from the Choose Your Own Adventure series, so if the book you're looking for was part of the CYOA series you'll likely find it there. The same article links to Demian's Gamebook Web Page, which may be helpful in its own right. That page also has an associated mailing list, so if you still don't find what you're looking for you might ask on that list.

It's interesting to note that many of the CYOA books are available used for $0.01 on Amazon, so you could collect 100 of them for $1 (plus $399 shipping!).

ContentLicense: CC BY-SA 2.5

Title: Fiction that includes BASIC programs

ContentLicense: CC BY-SA 3.0


问:
Creating Objects
I have a general coding standard question. Is it bad practice to initialize and create an object in multiple methods depending on the outcome of a users choice. So for example if the user quits a poker game, create the poker hand with the cards the user has received, even if < 5, and if the user played till the end create object to show completed hand to show outcome of the game. The key is that the object will only be created once in actuality, there are just different paths and parameters is will receive depending on if the user folded, or played on to the showdown.</p>

答:
A slightly different view on the problem - no, it's not always bad practice to initialize and create an object multiple times. There's even a pattern named Value Object that makes heavy use of object recreation if necessary.

A Hand could perfectly be an object, and a pretty good choice for a value object for that matter.

When you think of it, the poker domain is largely about hands - comparing players hands, adding cards to a hand, calculating probabilities from a hand, etc. So why not make Hand a first class domain object ? Yet a hand is quite anonymous, if there's an identity to it, it rather belongs to the player than the hand of cards itself. As Rocket Surgeon pointed out, chances are that Player is the only entity (with an identity), but not necessarily the only object.

I see several benefits to making Hand a (value) object :

You gain a lot of readability from making the concept explicit - passing a Hand around as a parameter, or comparing 2 Hands, is much more meaningful and immediately intention revealing than passing or comparing Players or arrays of Cards.

You can reuse the Hand anywhere you want, even outside of a Player.

If you go the value object route, you can make a Hand immutable. Thus you don't have to worry about changes in its state, wondering when and by whom your hand was modified. Threads that need to access your hand in parallel can do it without fear of concurrent modification problems.

Now from your original question, I'm not sure whether you're talking about a business Hand object or a graphical Hand object ("create object to show completed hand to show outcome of the game"). The instantiation and reuse of graphical objects is a whole other story.

Title: Creating Objects


问:
What is the definition of "Big Data"?
Is there one?

All the definitions I can find describe the size, complexity / variety or velocity of the data.

Wikipedia's definition is the only one I've found with an actual number

Big data sizes are a constantly moving target, as of 2012 ranging from a few dozen terabytes to many petabytes of data in a single data set.

However, this seemingly contradicts the MIKE2.0 definition, referenced in the next paragraph, which indicates that "big" data can be small and that 100,000 sensors on an aircraft creating only 3GB of data could be considered big.

IBM despite saying that:

Big data is more simply than a matter of size.

have emphasised size in their definition.

O'Reilly has stressed "volume, velocity and variety" as well. Though explained well, and in more depth, the definition seems to be a re-hash of the others - or vice-versa of course.

I think that a Computer Weekly article title sums up a number of articles fairly well "What is big data and how can it be used to gain competitive advantage".

But ZDNet wins with the following from 2012:

“Big Data” is a catch phrase that has been bubbling up from the high
  performance computing niche of the IT market... If one sits through
  the presentations from ten suppliers of technology, fifteen or so
  different definitions are likely to come forward. Each definition, of
  course, tends to support the need for that supplier’s products and
  services. Imagine that.

Basically "big data" is "big" in some way shape or form.

What is "big"? Is it quantifiable at the current time?

If "big" is unquantifiable is there a definition that does not rely solely on generalities?

答:
Great to see O'Reilly and others finally latch on to Gartner's 3Vs of big data that we first introduced over 11 years ago. For reference, here's the original piece I wrote in 2001: http://blogs.gartner.com/doug-laney/deja-vvvue-others-claiming-gartners-volume-velocity-variety-construct-for-big-data/.

Gartner's recently updated definition also recognizes the value aspect: "Big Data are information assets with volumes, velocities and/or variety requiring innovative forms of information processing for enhanced insight discovery, decision-making and process automation."

We have also developed a method to quantify data magnitude along the three vectors that are prescriptive in terms of technology adoption. However I cannot share it publicly.

Title: What is the definition of "Big Data"?


问:
Create new variable or make multiple chained calls?
What is the best way to get this attributes, thinking in performance and code quality?

Using chained calls:

```<code>    name = this.product.getStock().getItems().get(index).getName();
    id = this.product.getStock().getItems().get(index).getId();
</code>```

Creating new variable:

```<code>    final item = this.product.getStock().getItems().get(index);
    name = item.getName();
    it = item.getId();
</code>```

I prefer the second way, to let the code cleaner. But I would like to see some opinions about it.

Thank you!

答:
I prefer the second way as well because it shows intent. You are getting the name and it off of a single item you have retrieved.

In the first way, could there exist a possibility (e.g. via another thread) that .get(index) returns a different item between the two calls? If that could happen now, or in some future iteration of the software, the second way not only has the benefit I talk about above, but it may become necessary.


问:
Is constantly looking for code examples a sign of a bad developer?
I am a CS student with several years of experience in C and C++, and for the last few years I've been constantly working with Java/Objective C doing app development and now I have switched to web development and am mainly focused on ruby on rails and I came to the realization that (as with app development , really) I reference other code way too much. I constantly Google functionality for lots of things I imagine I should be able to do from scratch and it's really cracked my confidence a bit.

Basic fundamentals are not an issue, I hate to use this as an example but I can run through javabat in both java/python at a sprint - obviously not an accomplishment and but what I mean to say is I have a strong base for the fundamentals I think?

I know what I need to use typically but reference syntax constantly. Would love some advice and input on this, as it has been holding me back pretty solidly in terms of looking for work in this field even though I'm finishing my degree. My main reason for asking is not really about employment, but more that I don't want to be the only guy at a hackathon not hammering out nonstop code and sitting there with 20 Google/github tabs open, and I have refrained from attending any due to a slight lack of confidence...

Is a person a bad developer by constantly looking to code examples for moderate to complex tasks?

答:
I think reading code examples, and just reading source code of what other people have developed in general, is the best way to improve your skills. I really think it opens doors in your brain that would have not been opened otherwise.

If you think up a solution A, and someone else thinks up a solution B, when each of you share your solutions, you can realize solution C which may be even better than A or B.


问:
What are the drawbacks when designing a class?
When I read the book Effective Java chapter 4,  I met some sentences but I can't think them out :

What is the implementation when designing a class , why subclass will rely on the implementation detail of superclass?

Why will inheritance break encapsulation?

答:
This is really a comment to your comment, but it was too hard to write as a comment.

When a subclass inherit a super class , why does it depend on its
  super class's implementation details.This is what am I considered .I
  can't grasp the meaning of your first two sentence from your comment
  ,can you explain it in a more concrete way, or give me a link to
  another page with examples to describe it. –

Lets say you have a class that represents a deck of cards, and it has a method deal() that returns the top card off the deck, and a method shuffle() that shuffles the cards in the deck.

You sublcass it, and override shuffle, say, to make it a more random shuffle then the original class had.

Now, at some point in the future, someone edits the base class, and changes deal().  Originally it would take the card and deal it, and move the card to the bottom of the deck, So that eventually if you kept dealing you would get the card back, and the order would repeat.

But now, the method is changed so that deal will check to see if the card was already returned, and if it was, it will reshuffle automatically, once all the cards were dealt one time.

Your sublcass, will not know about this implementation change, and could exhibit strange behavior.  Lets say the shuffle method in your derived class is very slow, 3-4 seconds.  Now suddenly when dealing, there is a lag time due to the shuffle.  The base class does not show any issues, becuase its shuffle is very fast.

That is what they mean by depends on its super class's implementation details.


答:
So I see you mentioned that you're going to a hackathon. I've been to quite a few this past year (more than 15) and noticed that they are great for learning. And by great for learning I mean learning how to never code like that ever again. I mostly try to do something new at every hackathon I go to just so I can learn new things. As there is a huge time constraint, you rely on just copy pasting all the code you can find and this comes to bite you in the ass when you're testing it.

However, good things do come out of it, you: A) LEARN so much during bug testing (also cry heavily) B) Know to never code like that again and learn better coding practices. Also, at hackathons you'll meet people that can teach you so many new things you never knew about, and you'll do things you are never going to do in school.

So what I'm saying is copy pasting is bad, and you won't learn anything, and the time you saved by copy pasting will bite you later on during bug testing and you have no idea what you even wrote, it's 8 AM, and are fueled with all the caffeine. But, I think as long as you bug test your code, you will HAVE to learn everything you copied before.

Title: Is constantly looking for code examples a sign of a bad developer?

Body:
I am a CS student with several years of experience in C and C++, and for the last few years I've been constantly working with Java/Objective C doing app development and now I have switched to web development and am mainly focused on ruby on rails and I came to the realization that (as with app development , really) I reference other code way too much. I constantly Google functionality for lots of things I imagine I should be able to do from scratch and it's really cracked my confidence a bit.

Basic fundamentals are not an issue, I hate to use this as an example but I can run through javabat in both java/python at a sprint - obviously not an accomplishment and but what I mean to say is I have a strong base for the fundamentals I think?

I know what I need to use typically but reference syntax constantly. Would love some advice and input on this, as it has been holding me back pretty solidly in terms of looking for work in this field even though I'm finishing my degree. My main reason for asking is not really about employment, but more that I don't want to be the only guy at a hackathon not hammering out nonstop code and sitting there with 20 Google/github tabs open, and I have refrained from attending any due to a slight lack of confidence...

Is a person a bad developer by constantly looking to code examples for moderate to complex tasks?


问:
RDF and OWL: Have these delivered the promises of the Semantic Web?
These days I've been learning a lot about how different scientific fields are trying to move their data over to the Semantic Web in order to "free up data from being stored in isolated silos". I read a lot about how these fields are saying how their efforts are implementing the "visions" of the Semantic Web.

As a learner (and from purely a learning perspective) I was curious to know why, if semantic technology is deemed to be so powerful, the efforts have been around for years but myself and a lot of people I know have never even heard of it until very recently? Also, I don't come across any scholarly articles deeming "oh, our inferencing engine was able to make such and such discovery, which is helping us pave our way to solving...." etc.

It seems that there are genuine efforts across different institutions, fields, and disciplines to shift all their data to a "semantic" format, but what happens after all that's been done? All the ontologies have been created/unified, and then what?

答:
Dont agree one bit with the answer from faif. Basically state of SemWeb is as follows:

The really useful standards have only gone into recommendation quite recently. SPARQL 1.0 wasn't that useful, SPARQL 1.1 is UBER powerful. The RDF working group were also put on hiatus delaying the standardisation of Turtle (which is now imminent) and RDFj (RDF and JSON), meaning that new developers were generally constrained to RDF/XML (avoid like the plague).

Developers are using Semantic Web technology in anger. Look at http://www.semanticoverflow.com . Lots of activity, good questions. Infact your question has actually been asked on a number of occasions. FYI it used to be a part of the stackexchange family, but got bought by a VC.

Companies are using Semantic Web technology. BBC is a very big user, Volkswagen UK, Google (the new Google KnowledgeGraph, schema.org, Rich Snippets), Facebook (the entire data graph API returns RDF when requested), Wikipedia (DBPedia, WikiData) and many many more.

So in summary, its going to be a silent revolution, but you need to get on board, because when the paradigm shift comes, it is going to be a big one.


问:
What's the difference between using RDFS/OWL versus XML?
I was wondering what advantages the ontology languages of RDFS/OWL has over using a tagging/markup system (such as http://www.schema.org/) for managing and creating metadata?</p>

答:
Couldn't diagree more with ZJR's answer. It is utterly uninformed.

How do you parse Microdata? What does it parse too? RDFa parses to RDF, a common data model that is the thing the Semantic Web has been crying out for. Microdata basically came about because Hickie couldn't be bothered to read the RDF and RDFa specs. It might be easier for a developer, but it's not better for the web (i.e lazy)

For a listing of common OWL vocabularies see below:

http://vocab.org/, http://open.vocab.org/

http://schemapedia.com/

http://prefix.cc/

http://rdfs.org/ns/

http://www.sindice.com/

http://watson.kmi.open.ac.uk/

http://rdfdata.org/

http://esw.w3.org/VocabularyMarket

http://www.umbel.org/lod_constellation.html

http://www.schemaweb.info/

http://swoogle.umbc.edu/

http://schemacache.com/

The next release of RDF is imminent, including new serialisation formats such as Turtle and RDFj

SPARQL 1.1 is also dues imminently. Query federation, property path expression, SPARQL Update and much much more.

The BBC is built on RDF. The Facebook graph API provides RDF (thats right, you can deference a graph URI using the text/turtle Accepts header and get back RDF) and many other big corporations.

So in summary Semantic Web, RDF, RDFS, OWL, SPARQL and all the Semantic Web standards are very much alive and kicking. If you don't believe me, have a look at all the activity on http://www.semanticoverflow.com


答:
Software development in a corporate settings requires a fair amount of code reuse. Why rewrite a function/method if an API already exists and is widely used? It most likely will be just as efficient as anything you write and take less time.

Of course, succeeding in software development also requires a break from the keyboard, so that you can read and comprehend what is really going on. Take any web framework. You should know what is going on underneath so you understand the code you are writing, but you likely will never have to write a web framework from scratch yourself.

You just have to write code which takes advantage of the type of framework (say a component-based framework requires a certain style) and this comes from understanding the larger picture. Learn the larger picture and you will be fine.


问:
What are Some Real World Usage Scenarios for node.js
i would like to begin tinkering with Node.js but i am unsure of some "Real-World" situations where node.js would be considered the proper thing to be used. The last thing a developer wants is to learn a new technology and use it in-properly..

Can you provide real-world examples of where node.js would be used properly

答: Web apps server side, that is, apps that handle lots of network traffic and optionally lots of disk traffic. Node.js's main strength is non-blocking io (network as well as disc).</p>


答:
I like niether, personnaly.

If any of them returns a null you get a nullpointer exception on the line...

Now... which one of them did go wrong ?

Now, method chaining can be and is very usefull with some specific usage patterns.  Say for example in a fluent type interface (most mocking framework will do this, at least the ones I`ve seen).

Ideally one should strive to reduce coupling and this pattern does exactly the opposite.

From experience when I find myself having to dig deep in my object structure to do a task it usually is an indicator that my object structure or my business logic is not right.  Perhaps the work could be buried deeper through  some kind of wrapper object / facade /  delegate and just call that instead.  Perhaps your function or method is doing too much and should be split in smaller, more specialized chunks.  Perhaps the object needs to expose properties of the items inside instead of exposing the item as a whole.  It all depends on your architecture and use cases.

That said, software needs to be shipped and that usually means some parts will be more hackish than others, Ideally these should be well isolated bounded and boxed and method chaining like this weather done through successive variable assignement or directly tends to break these boundaries reducing the overall stability.

Title: Create new variable or make multiple chained calls?

Body:
What is the best way to get this attributes, thinking in performance and code quality?

Using chained calls:

```<code>    name = this.product.getStock().getItems().get(index).getName();
    id = this.product.getStock().getItems().get(index).getId();
</code>```

Creating new variable:

```<code>    final item = this.product.getStock().getItems().get(index);
    name = item.getName();
    it = item.getId();
</code>```

I prefer the second way, to let the code cleaner. But I would like to see some opinions about it.

Thank you!


问:
Help with Abstract Factory Pattern
I need help with a abstract factory pattern design. This question is a continuation of: Design help with parallel process

I am really confused where I should be initializing all of the settings for each type of medium (ex: RS232, TCP/IP, etc).

Attached is the drawing on how I am setting up the pattern:

As shown, when a medium is created, each medium imposes a ICreateMedium interface. I would assume that the Create() method also create the proper object, such as SerialPort serialPort = new SerialPort("COM1", baud); however, TCPIPMedium would have an issue with the interface because it wouldn't need to initialize a serial port object.

I know I am doing something majorly wrong here. I just can't figure it out and have been stuck for a while.

What I also get confused on show the interface IMedium will get access to the communication object once it is created so it can write out the appropriate byte[] packet.

Any guidance would be greatly appreciated. My main goal is to have the Communicator class spit a packet out without caring which type of medium is active.

答:
In this case, if the RS232Medium constructor requires a SerialPort then the RS232 Factory, RS232MediumCreate as you have called it, will need to have that port already stored inside it:

(sorry about the Java)

```<code>class RS232MediumCreate implements ICreateMedium {
    SerialPort port;

    RS232MediumCreate(SerialPort port) {
        this.port = port;
    }

    @Override
    public IMedium Create() {
        return new Rs232Medium(port);
    }
}
</code>```

Now your usage of Communicator looks like this:

```<code>void getMediumFrom(ICreateMedium factory) {
    IMedium medium = factory.Create();

    //...
}
</code>```

and your usages of that method will look like this:

```<code>communicator.getMediumFrom(new RS232MediumCreate(new SerialPort("COM1"), baud));
</code>```

When using an Abstract Factory Pattern, as you mentioned, your interfaces must align and so any differences in required parameters for the final object must be accounted for in the corresponding Factory.

That means that Factory must already know about what parameters will be used.  This is a consequence of the Factory pattern, and to work around it would defeat the purpose of using an abstract factory.

Title: Help with Abstract Factory Pattern

Body:
In this case, if the RS232Medium constructor requires a SerialPort then the RS232 Factory, RS232MediumCreate as you have called it, will need to have that port already stored inside it:

(sorry about the Java)

class RS232MediumCreate implements ICreateMedium {
    SerialPort port;

    RS232MediumCreate(SerialPort port) {
        this.port = port;
    }

    @Override
    public IMedium Create() {
        return new Rs232Medium(port);
    }
}

Now your usage of Communicator looks like this:

void getMediumFrom(ICreateMedium factory) {
    IMedium medium = factory.Create();

    //...
}

and your usages of that method will look like this:

communicator.getMediumFrom(new RS232MediumCreate(new SerialPort("COM1"), baud));

When using an Abstract Factory Pattern, as you mentioned, your interfaces must align and so any differences in required parameters for the final object must be accounted for in the corresponding Factory.

That means that Factory must already know about what parameters will be used.  This is a consequence of the Factory pattern, and to work around it would defeat the purpose of using an abstract factory.


问:
Advice for learning Javascript with prior knowledge of C++?
Recently I have become interested in learning Javascript for web development. I currently know HTML, CSS, and beginner/intermediate C++. I understand polymorphism, inheritance, and all of that fun stuff. Would any of these skills carry over to Javascript? In what key ways does Javascript differ from C++? </p>

答:
Do you know Design Patterns?

The reason being that this really helps in the transition. It may be beneficial to realize that the following patterns have specific importance in JavaScript:

Namespace (Module)
Pub-Sub (Observer).

It is important to understand the Module Pattern in JavaScript, and how it relates to global scope specifically. I would impart that private member variables and classical object-oriented design are different.

JS is flexible because it doesn't have a class.In JS... it is all just objects, at runtime - operating on the DOM(important). JavsScript objects are essentially one in the same to the notion of JSON, 'discovered' by Douglas Crockford. He is one expert.

JSON is a JavaScript Object transfer format that is used in AJAX applications. It is possible to pass these objects... all over, regarding node.js

Inheritance is different in JavaScript. One very fine presenter defined it as: "JavaScript is friendly to you - It wont yell at you during errors." and "Inheritance is like a backpack, you just put stuff in it"-venkat submariam at RWX.

MVC is also super important in my humble opinion. I like backbone.js there are others.

It is a great language highly recommend it! It has been great since my transition from c++; and sure do miss arduino.

peace~


答:
Full disclosure - I am an old person who was trained in a different pre-Internet available at work era. I've watched the skills of the younger developers steadily deteriorate mostly due to them not retaining information or understanding the solution they grabbed from the Internet. I've observed that the level of competence a person had after 1-2 years of experience, 20 years ago, is now the level of competence someone has after 5-7 years of experience. (Yes that is a personal observation but I've done a lot of hiring, I have no statistical data on the matter and yes, I am sometimes old and cranky, take this statement with a grain of salt. And stay off my yard.)

Looking up everything is inefficient in terms of time. It also is a symptom of someone who doesn't have much depth of knowledge. People with depth of knowldge can write code faster than people who don't know how to solve a problem without looking things up. So it is worth it to learn to handle more things without having to look things up continually.

Now I'm not saying you should never look things up, I'm saying you should learn to retain knowledge and only need to look up things you use rarely or when you encounter a genuinely new issue or language or paradigm. And I'm not saying you shouldn't be reading to keep up with new solutions and tools and languages.

My real concern with developers who look up things too often that that too many of them (not necessarily you) never develop the analytical skills to understand the problems they have and the solutions that are needed. Read how many questions there are where the person puts in the error message that he or she clearly doesn't understand, but which should be quite clear to anyone operating at the professional level. Or the ones where the person says, "it's not working, why?" with no reference to the error message or how it isn't working and the code is syntactically correct. Or the ones who are given a piece of code that should work, but in the haste to answer first the person has made an obvious syntax error (like say missing the ON keyword in a SQL join to use an example I saw just today) and the poster comes back with I get an error on line 12. Why yes, if you look at line 12 it obvious what the error is if you have  baseline competence.

So if what you are looking up is stuff that is part of the core functionality of the language(s) (BTW this should include SQL if you are accessing databases) you have used for more than six months, I suspect you are looking up too much. If what you are looking up are advanced features, especially those you might use rarely, then you are doing fine.

But how to you learn to retain more information?  First understand why the code broke. Even if someone gives you a working solution, if you don't see why that worked and yours did not, then ask. If you don't understand the error message then ask what it meant and then try to solve it yourself.

And never cut and paste a solution you don't understand. In fact, don't cut and paste at all. If you want to retain information, you need to do the typing of it. Actually physically writing the code yourself helps you learn it. That is a well-known learning technique.

Practice generalizing your understanding of the code. I've seen people ask similar questions over and over again over time because they don't understand that the solution they got a month ago to problem ABC is the same solution to the new problem DEF.

So when you've researched something, take some time to think about what types of problems it would be good for solving and write yourself notes about that. Then when you have a problem to solve, first check your own notes to see of you have already noted a possible technique.  If you evaluate multiple ways to solve a problem, take notes on the type of problem, the possible solutions you looked at and the pros and cons of each one.  Again the note taking is helping solidify the knowledge in your brain, you already have your own thought process in terms of the pros and cons worked out and don't have to do that again (or at least not in as much depth, you may still look for more possible techniques) for the next similar problem.

And when deciding what to learn next, go for some depth in one of your main technologies before jumping into learning the first 30 days worth of yet another technology (this assumes you have enough breadth of knowledge to actually perform your job, if you need to use 6 technologies - get the basics in all six first before going for depth). Then go back and forth, learning new stuff, at a basic level, learning something in more depth, then learning more new technologies at a basic level. If you do this over time, you will find that your basic level of what you want out of a new technology is much deeper because you understand more advanced questions to ask about it.

Another way to learn to retain knowledge is to teach it to someone else. Answer questions at places like this, present training topics to your team, make presentations at your local user groups, write blog entries and help maintain a wiki of information at your company to help other developers.


问:
null pointers vs. Null Object Pattern
Attribution: This grew out of a related P.SE question

My background is in C / C++, but I have worked a fair amount in Java and am currently coding C#.  Because of my C background, checking passed and returned pointers is second-hand, but I acknowledge it biases my point of view.

I recently saw mention of the Null Object Pattern where the idea is that an object is always returned.  Normal case returns the expected, populated object and the error case returns empty object instead of a null pointer.  The premise being that the calling function will always have some sort of object to access and therefore avoid null access memory violations.

So what are the pros / cons of a null check versus using the Null Object Pattern?

I can see cleaner calling code with the NOP, but I can also see where it would create hidden failures that don't otherwise get raised.  I would rather have my application fail hard (aka an exception) while I'm developing it than have a silent mistake escape into the wild.

Can't the Null Object Pattern have similar problems as not performing a null check?

Many of the objects I have worked with hold objects or containers of their own.  It seems like I would have to have a special case to guarantee all of the main object's containers had empty objects of their own.  Seems like this could get ugly with multiple layers of nesting.

答:
You wouldn't use a Null Object Pattern in places where null (or Null Object) is returned because there was a catastrophic failure. In those places I would continue to return null. In some cases, if there's no recovery, you might as well crash because at least the crash dump will indicate exactly where the problem occurred. In such cases when you add your own error handling, you are still going to kill the process (again, I said for cases where there's no recovery) but your error handling will mask very important information that a crash dump would've provided.

Null Object Pattern is more for places where there's a default behavior that could be taken in a case where object isn't found. For example consider the following:

```<code>User* pUser = GetUser( "Bob" );

if( pUser )
{
    pUser->SetAddress( "123 Fake St." );
}
</code>```

If you use NOP, you would write:

```<code>GetUser( "Bob" )->SetAddress( "123 Fake St." );
</code>```

Note that this code's behavior is "if Bob exists, I want to update his address". Obviously if your application requires Bob to be present, you don't want to silently succeed. But there are cases where this type of behavior would be appropriate.  And in those cases, doesn't NOP produce a much cleaner and concise code?

In places where you really can't live without Bob, I would have GetUser() throw an application exception (i.e. not access violation or anything like that) that would be handled at a higher level and would report general operation failure. In this case, there's no need for NOP but there's also no need to explicitly check for NULL. IMO, those checks for NULL, only make the code bigger and take away from readability.  Check for NULL is still the right design choice for some interfaces, but not nearly as many as some people tend to think.

Title: null pointers vs. Null Object Pattern

Body:
You wouldn't use a Null Object Pattern in places where null (or Null Object) is returned because there was a catastrophic failure. In those places I would continue to return null. In some cases, if there's no recovery, you might as well crash because at least the crash dump will indicate exactly where the problem occurred. In such cases when you add your own error handling, you are still going to kill the process (again, I said for cases where there's no recovery) but your error handling will mask very important information that a crash dump would've provided.

Null Object Pattern is more for places where there's a default behavior that could be taken in a case where object isn't found. For example consider the following:

User* pUser = GetUser( "Bob" );

if( pUser )
{
    pUser->SetAddress( "123 Fake St." );
}

If you use NOP, you would write:

GetUser( "Bob" )->SetAddress( "123 Fake St." );

Note that this code's behavior is "if Bob exists, I want to update his address". Obviously if your application requires Bob to be present, you don't want to silently succeed. But there are cases where this type of behavior would be appropriate.  And in those cases, doesn't NOP produce a much cleaner and concise code?

In places where you really can't live without Bob, I would have GetUser() throw an application exception (i.e. not access violation or anything like that) that would be handled at a higher level and would report general operation failure. In this case, there's no need for NOP but there's also no need to explicitly check for NULL. IMO, those checks for NULL, only make the code bigger and take away from readability.  Check for NULL is still the right design choice for some interfaces, but not nearly as many as some people tend to think.


问:
 Why do so many developers do this in their HTML?
```<code> <body>
  <!-- wrapper -->
  <div id="wrapper">
   <!-- title -->
   <div id="title"><img src="title.png" alt="" /></div>

   <!-- form wrapper -->
   <div id="form_wrapper">

    <!-- form -->
    <form action="thankyou.php" method="POST">
     <!-- ... ... -->
    </form>
    <!-- /form -->
   </div>
   <!-- /form wrapper -->
  </div>
  <!-- /wrapper -->
 </body>
</code>```

I can almost understand the  at the end, because it's so far from the start of the tag/pair...  but seriously, what's the point of the opening comment lines?  I wouldn't ask the question if I didn't see this all the time.

I feel as if I'm missing something.  Maybe there's some unwritten best-practice involved, though I fail to comprehend what it could possibly be.  More than likely it's just obsessive-compulsive behavior.

How do you guys normally comment your markup, if at all?

答:
Usually my markup is generated dynamically so comments are not included... but when I do write markup I will have:

```<code><!-- start BLOCK-->
  html markup
<!-- close BLOCK-->
</code>```

It makes it easier for me to see where major blocks/divs are within my code.

Title: <!-- open --> Why do so many developers do this in their HTML? <!-- /close -->

Body:
Usually my markup is generated dynamically so comments are not included... but when I do write markup I will have:

<!-- start BLOCK-->
  html markup
<!-- close BLOCK-->

It makes it easier for me to see where major blocks/divs are within my code.


问:
What are the legal risks if any of using a GPL or AGPL Web Application Framework/CMS?
Tried to ask this on SO but was referred here...

Am I correct in saying that using a GPL'ed web application framework such as Composite C1 would NOT obligate a company to share the source code we write against said framework?

That is the purpose of the AGPL, am I correct?

Does this also apply to Javascript frameworks like KendoUI?

The GPL would require any changes that we make to the framework be made available to others if we were to offer it for download.

In other words, merely loading a web sites content into my browser is not "conveying" or "distributing" that software.

I have been arguing that we should avoid GPL web frameworks and now after researching I am pretty sure I am wrong but wanted to get other opinions?

Seth

答: That is correct, GPL only matters when you are distributing the binary version of the code. If you never intend to distribute the code then GPL is irrelevant. There can still be a case for avoiding GPL because you may want to distribute your modifications some day, and the GPL could come back to bite you. There are ways, however,  to "include" a GPL library while avoiding being forced to release your changes as well, but they do violate the spirit of the GPL if bad karma worries you.</p>


问:
Git bug branching convention
I've been following the successful Git branching model guide for most of my development. I still wonder if the way I handle bug tickets is correct.

My current workflow: Once I accept a bug ticket I will do a git checkout -b bug/{ticket_number}, create a single commit as a fix and then checkout develop and do a git merge --no-ff.

I'd love to hear from the experiences of others whether or not I am abusing the --no-ff option in this instance. If I am, could someone suggest a better approach?

答:
You don't need to do all your work as a single commit; you can commit multiple times and squash the commits when you merge back into the original branch (which is the default merge behavior). If the bug is significant, that might be helpful.

Also, if the branch is open for a long time, you might want to rebase the branch (basically, recreate the branch from a newest root version and apply your changes again); this will update the branch with the upstream changes and you'll be able to verify if any change upstream has broken your bugfix.

After you have pushed your branch upstream, however  (in case you do that), rebasing is not recommended. You can create a new branch from the root and merge your old branch into the new. This seems to work, but I'm not sure if it's correct.

Title: Git bug branching convention


问:
TDD: Write a separate test for object initialization or relying on other tests exercising it
This seems to be the common pattern that's emerging in some of the tests I've worked on lately.  We have a class, and quite often this is legacy code whose design can't be easily altered, which has a bunch of member variables.

There's some kind of "Initialize" or "Load" function which would put an object into a valid state. Only after it is initialized/loaded, are the members in the proper state so that other methods can be exercised.

So when we start writing tests, first test is "TestLoad" and all we put in there is exercising initialization logic. Then we might add one (or few) TestLoadFailureXXX tests and those are definitely valuable.

Then we start writing tests to verify other behaviors but all of them require the object to be loaded. So they all start by running exactly the same code as "TestLoad".

So my question: Is TestLoad even necessary? Do you take it out and let other tests simply exercise the loading? Or leave it so things are more explicit?

I know that each unit test function should have no (or as little as possible) overlap with other test functions, but it seems like in cases of loading, this is unavoidable. And whether we like it or not, if something in the loading code breaks, we will end up with a whole test suite of failures.

Is there another approach that I might be missing here?

Thank you for the responses. It definitely makes sense that you want to see "InitializationTest" and if that fails you know where to start looking.

In case it matters, this question is mostly about C++ and we use CppUnit framework. And now, thanks to sleske, I'll be constantly wishing that CppUnit supported test dependencies.  Might have to hack something in one of these days :)

答:
If the initialization fails, you would like that to show up in a test clearly labeled as testing the initialization, instead of in a test which nominally is about something else.

And if behavior dependant on initialization fails, when a test catches it, you would like to be confident that the error is in the nominally tested behavior, and not the initialization, which was covered in a seperate test.

So having a seperate initialization test helps you distinguish between different error conditions.


答:
I like the idea of "test as documentation". So when initializing a class, it should be in a specific state, I would say that there should be a test verifying that it is actually in that specific state after initialization, or that it performs some specific operation during initialization. Simply because it works as documentation for the expected behavior of the initialization logic.

Is TestLoad even necessary?

Well, probably not "necessary" as such. But I think that it is a good idea. Remember, the test is also an indicator which part of the code that fails, when you introduce a bug. Having an explicit unit test for the initialization code can help you more quickly identify that it is the initialization logic that is at fault.

But when you say that all the tests run the exact same code as TestLoad, it sounds like you could exercise a little more code reuse in your test code, share the initialization code across tests.

Title: TDD: Write a separate test for object initialization or relying on other tests exercising it

Body:
This seems to be the common pattern that's emerging in some of the tests I've worked on lately.  We have a class, and quite often this is legacy code whose design can't be easily altered, which has a bunch of member variables.

There's some kind of "Initialize" or "Load" function which would put an object into a valid state. Only after it is initialized/loaded, are the members in the proper state so that other methods can be exercised.

So when we start writing tests, first test is "TestLoad" and all we put in there is exercising initialization logic. Then we might add one (or few) TestLoadFailureXXX tests and those are definitely valuable.

Then we start writing tests to verify other behaviors but all of them require the object to be loaded. So they all start by running exactly the same code as "TestLoad".

So my question: Is TestLoad even necessary? Do you take it out and let other tests simply exercise the loading? Or leave it so things are more explicit?

I know that each unit test function should have no (or as little as possible) overlap with other test functions, but it seems like in cases of loading, this is unavoidable. And whether we like it or not, if something in the loading code breaks, we will end up with a whole test suite of failures.

Is there another approach that I might be missing here?

Thank you for the responses. It definitely makes sense that you want to see "InitializationTest" and if that fails you know where to start looking.

In case it matters, this question is mostly about C++ and we use CppUnit framework. And now, thanks to sleske, I'll be constantly wishing that CppUnit supported test dependencies.  Might have to hack something in one of these days :)


答:
As the other answers already pointed out, having a separate test just for the initialization is useful, because if this test fails, you know that any other failing tests are probably due to the initialization, so it makes sense to tackle that first.

For bonus points, you might want to use a testing framework that has test dependencies (such as TestNG). Then you can mark all other tests for the class as dependent on the initialization test. Then, if the init test fails, the other tests will be skipped (with an appropriate note). That way you can see immediately where you need to start searching for the problem.


答:
So what are the pros / cons of a null check versus using the Null Object Pattern?

Pros

A null check is better since it solves more cases. Not all objects have a sane default or no-op behavior.

A null check is more solid. Even objects with sane defaults are used in places where the sane default isn't valid. Code should fail close to the root cause if it's going to fail. Code should fail obviously if it is going to fail.

Cons

Sane defaults usually result in cleaner code.

Sane defaults usually result in less catastrophic errors if they manage to get into the wild.

This last "pro" is the main differentiator (in my experience) as to when each should be applied. "Should the failure be noisy?". In some cases, you want a failure to be hard and immediate; if some scenario that should never happen somehow does. If a vital resource wasn't found... etc. In some cases, you're okay with a sane default since it's not really an error: getting a value from a dictionary, but the key is missing for example.

Like any other design decision, there are upsides and downsides depending on your needs.

Title: null pointers vs. Null Object Pattern

Body:
Attribution: This grew out of a related P.SE question

My background is in C / C++, but I have worked a fair amount in Java and am currently coding C#.  Because of my C background, checking passed and returned pointers is second-hand, but I acknowledge it biases my point of view.

I recently saw mention of the Null Object Pattern where the idea is that an object is always returned.  Normal case returns the expected, populated object and the error case returns empty object instead of a null pointer.  The premise being that the calling function will always have some sort of object to access and therefore avoid null access memory violations.

So what are the pros / cons of a null check versus using the Null Object Pattern?

I can see cleaner calling code with the NOP, but I can also see where it would create hidden failures that don't otherwise get raised.  I would rather have my application fail hard (aka an exception) while I'm developing it than have a silent mistake escape into the wild.

Can't the Null Object Pattern have similar problems as not performing a null check?

Many of the objects I have worked with hold objects or containers of their own.  It seems like I would have to have a special case to guarantee all of the main object's containers had empty objects of their own.  Seems like this could get ugly with multiple layers of nesting.


问:
Object Oriented programming on 8-bit MCU Case Study
I see that there's a lot of questions related to OO Programming here. I'm actually trying to find a specific resource related to embedded OO approaches for an 8 bit MCU.

Several years back (maybe 6) I was looking for material related to Object Oriented programming for resource constrained 8051 microprocessors. I found an article/website with a case history of a design group that used a very small RAM part, and implemented many Object based constructs during their C design and development. I believe it was an 8051. The project was a success, and managed to stay inside the very small ROM/RAM they had available.

I'm attempting to find it again, but Google can't locate it. The article was well written, and recommended a "mixed" approach using C methods for inheritance and encapsulation - if I recall correctly.

Can anyone help me locate this article?

答:
I suspect you're not referring to Embedded C++ or Wikipedia on Embedded C++

This 8051 projects forum appeared to have something similar to what you were talking about.

And there, the magic search terms appear to be

```www.engg.le.ac.uk/books/Pont/ec51.htm
www.engg.le.ac.uk/books/Pont/ec51bugs.pdf
www.le.ac.uk/engineering/mjp9/pttesguide.htm
```

The first two URLs redirect to the Leicester Engineering site.  The last one goes through.
And a google search of that reveals some hits that are also linked to from the third link.  You may be able to find the professor who owns the course and see if the pdf is available.

This is the Professor's site

Body:
I suspect you're not referring to Embedded C++ or Wikipedia on Embedded C++

This 8051 projects forum appeared to have something similar to what you were talking about.

And there, the magic search terms appear to be

www.engg.le.ac.uk/books/Pont/ec51.htm
www.engg.le.ac.uk/books/Pont/ec51bugs.pdf
www.le.ac.uk/engineering/mjp9/pttesguide.htm

The first two URLs redirect to the Leicester Engineering site.  The last one goes through.
And a google search of that reveals some hits that are also linked to from the third link.  You may be able to find the professor who owns the course and see if the pdf is available.

This is the Professor's site


问:
Single Responsibility Principle - How Can I Avoid Code Fragmentation?
I'm working on a team where the team leader is a virulent advocate of SOLID development principles. However, he lacks a lot of experience in getting complex software out of the door.

We have a situation where he has applied SRP to what was already quite a complex code base, which has now become very highly fragmented and difficult to understand and debug.

We now have a problem not only with code fragmentation, but also encapsulation, as methods within a class that may have been private or protected have been judged to represent a 'reason to change' and have been extracted to public or internal classes and interfaces which is not in keeping with the encapsulation goals of the application.

We have some class constructors which take over 20 interface parameters, so our IoC registration and resolution is becoming a monster in its own right.

I want to know if there is any 'refactor away from SRP' approach we could use to help fix some of these issues. I have read that it doesn't violate SOLID if I create a number of empty coarser-grained classes that 'wrap' a number of closely related classes to provide a single-point of access to the sum of their functionality (i.e. mimicking a less overly SRP'd class implementation).

Apart from that, I cannot think of a solution which will allow us to pragmatically continue with our development efforts, while keeping everyone happy.

Any suggestions ?

答:
The answer is maintainability and clarity of code above all else. For me that that means writing less code, not more. Less abstractions, less interfaces, less options, less parameters.

Whenever I evaluate a code restructure, or adding a new feature I think about how much boilerplate will be required compared to the actual logic. If the answer is more than 50%, it probably means I'm over thinking it.

On top of SRP, there are many other development styles. In your case its sounds like YAGNI is definitely lacking.

OwnerDisplayName: Dean Chalk


问:
displaying multi-section html documents - best practices
I work at a research organization and we publish a lot of large-ish documents, usually organized in sections. What I want to know is how best to present these multi-section documents on our website.

Presently, what I do is load the entire document as a single page, with each section as its own div. Then I show and hide divs as needed via a table of contents and "next" and "prev" buttons.

The advantages to this are mainly: 1) that you can move between sections very quickly, 2) it produces consistent analytics (when a page is loaded, I know a report is being read).

The disadvantages, however, are real:

Readers can't take advantage of browser back/forward buttons to move between sections.

It's complicated to create direct links to individual sections (I can do it with javascript but it's not easy for other people to grab and share).

For long reports, you have to wait for the full report to load before you can move around (and that can include hordes of images and charts).

Do other people have thoughts on better ways to organize this? Here's an example of the current system: http://massbudget.org/825

答:
Front-End Templating may be a useful solution for you. There are many frameworks to choose from and they have risen in popularity in recent years. Two examples are underscore.js and handlebars.js. Also, Mustache.

These may be useful as a corresponding implementation of AJAX.

If you find yourself duplicating your  layout over and over... templating is a nice workflow and maintenance optimization.

Also, you would have to check the support for history, anchoring, and lazy-loading - but it is quite likely that a good templating engine would solve your three defined disadvantages.

link to example comparison.

All the best, Nash


答:
In AAA-style (arrange, act, assert -- eg. xUnit) testing, I just don't see the point. I understand the argument that it gives you a specific test that fails, but that really doesn't add anything. The fact that 10 tests all fall over in object initialisation really should be enough of a clue.

But, that said, this is one of many reasons I prefer the context/specification style of testing (eg. rSpec in Ruby -- few Rails programmers seem to use the default framework). It just removes the question. You initialise once in the context and if the context fails then the specifications never run.


问:
What does it mean to do a "null check" in C or C++?
I have been learning C++ and I am having a hard time understanding null. In particular, the tutorials I have read mention doing a "null check", but I am not sure what that means or why it's necessary.

What exactly is null?

What does it mean to "check for null"?

Do I always need to check for null?

Any code examples would be much appreciated.

答:
The null pointer value represents a well-defined "nowhere"; it is an invalid pointer value that is guaranteed to compare unequal to any other pointer value.  Attempting to dereference a null pointer results in undefined behavior, and will usually lead to a runtime error, so you want to make sure a pointer is not NULL before attempting to dereference it.  A number of C and C++ library functions will return a null pointer to indicate an error condition.  For example, the library function malloc will return a null pointer value if it cannot allocate the number of bytes that have been requested, and attempting to access memory through that pointer will (usually) lead to a runtime error:

```<code>int *p = malloc(sizeof *p * N);
p[0] = ...; // this will (usually) blow up if malloc returned NULL
</code>```

So we need to make sure the malloc call succeeded by checking the value of p against NULL:

```<code>int *p = malloc(sizeof *p * N);
if (p != NULL) // or just if (p)
  p[0] = ...;
</code>```

Now, hang on to your socks a minute, this is going to get a bit bumpy.

There is a null pointer value and a null pointer constant, and the two are not necessarily the same.  The null pointer value is whatever value the underlying architecture uses to represent "nowhere".  This value may be 0x00000000, or 0xFFFFFFFF, or 0xDEADBEEF, or something completely different.  Do not assume that the null pointer value is always 0.

The null pointer constant, OTOH, is always a 0-valued integral expression.  As far as your source code is concerned, 0 (or any integral expression that evaluates to 0) represents a null pointer.  Both C and C++ define the NULL macro as the null pointer constant.  When your code is compiled, the null pointer constant will be replaced with the appropriate null pointer value in the generated machine code.

Also, be aware that NULL is only one of many possible invalid pointer values; if you declare an auto pointer variable without explicitly initializing it, such as

```<code>int *p;
</code>```

the value initially stored in the variable is indeterminate, and may not correspond to a valid or accessible memory address.  Unfortunately, there's no (portable) way to tell if a non-NULL pointer value is valid or not before attempting to use it.  So if you're dealing with pointers, it's usually a good idea to explicitly initialize them to NULL when you declare them, and to set them to NULL when they're not actively pointing to anything.

Note that this is more of an issue in C than C++; idiomatic C++ shouldn't use pointers all that much.

Body:
The null pointer value represents a well-defined "nowhere"; it is an invalid pointer value that is guaranteed to compare unequal to any other pointer value.  Attempting to dereference a null pointer results in undefined behavior, and will usually lead to a runtime error, so you want to make sure a pointer is not NULL before attempting to dereference it.  A number of C and C++ library functions will return a null pointer to indicate an error condition.  For example, the library function malloc will return a null pointer value if it cannot allocate the number of bytes that have been requested, and attempting to access memory through that pointer will (usually) lead to a runtime error:

int *p = malloc(sizeof *p * N);
p[0] = ...; // this will (usually) blow up if malloc returned NULL

So we need to make sure the malloc call succeeded by checking the value of p against NULL:

int *p = malloc(sizeof *p * N);
if (p != NULL) // or just if (p)
  p[0] = ...;

Now, hang on to your socks a minute, this is going to get a bit bumpy.

There is a null pointer value and a null pointer constant, and the two are not necessarily the same.  The null pointer value is whatever value the underlying architecture uses to represent "nowhere".  This value may be 0x00000000, or 0xFFFFFFFF, or 0xDEADBEEF, or something completely different.  Do not assume that the null pointer value is always 0.

The null pointer constant, OTOH, is always a 0-valued integral expression.  As far as your source code is concerned, 0 (or any integral expression that evaluates to 0) represents a null pointer.  Both C and C++ define the NULL macro as the null pointer constant.  When your code is compiled, the null pointer constant will be replaced with the appropriate null pointer value in the generated machine code.

Also, be aware that NULL is only one of many possible invalid pointer values; if you declare an auto pointer variable without explicitly initializing it, such as

int *p;

the value initially stored in the variable is indeterminate, and may not correspond to a valid or accessible memory address.  Unfortunately, there's no (portable) way to tell if a non-NULL pointer value is valid or not before attempting to use it.  So if you're dealing with pointers, it's usually a good idea to explicitly initialize them to NULL when you declare them, and to set them to NULL when they're not actively pointing to anything.

Note that this is more of an issue in C than C++; idiomatic C++ shouldn't use pointers all that much.


答:
If a developer/student goes to say.. Wikipedia.. to copy/paste code into their project, then simply tries to get it to "work" then the only skills this person is developing is 'How to google'.  There might be some process of osmosis there, but not a whole bunch.  (You wouldn't believe how many people do this in college courses)

HOWEVER, If you analyze other peoples code and really think about what is going on in the code itself, then that does not make a person a bad developer.  It makes them a determined developer and probably indicates a learning style that is more tactile or visual.  I learn by example very well.  If someone tells me something or tries to explain it to me, I usually ask them to show me wtf they are talking about.

Looking, analyzing, and learning from code actually makes them a good developer over time, because they are reading and learning in the language they are using.

I often joke that I know the ins and outs of computer languages than I do my native English language. Which begs the question; "Will you explain that to me in Java plz?"


问:
Is there a way to track data structure dependencies from the database, through the tiers, all the way out to a web page?
When we design applications, we generally end up with the same tiered sets of data structures:

A persistent data structure that is described using DDL and implemented as RDBMS tables and columns.

A set of domain objects that consist primarily of data structures, usually combined with business-rule level logic, that are implemented in a programming language such as Java.

A set of service layer interfaces that directly support use case implementations (which use the domain data structures as parameters), implemented as EJBs or something equivalent in another programming language.

UI screens that allow users to C reate, R etrieve, U pdate, and (maybe) D elete all manner of data structures and graphs of data structures, with numerous screens and with multiple UI widgets, all structured to support the same data structures.

But if you want to change the data structures in any of these tiers, it always seems extremely difficult to assess the impact(s) the change will have across the application. UML can help, but tracing through diagram after diagram is not a real solution to this problem. The best I have ever seen was a homespun data tracking spreadsheet document that listed all of the data structures and walked the relationships from tier-to-tier.

Is there a tool or accepted approach that makes it easy to identify a data structure in any tier and easily obtain a list of all dependent:

database table and column data structures

domain object data structures

service layer interface methods and parameter data structures

screen & UI component data structures

答: I'd focus on the application server log as it frequently has entries for view calls, controller actions and database calls.</p>


问:
Do you start migrating your Swing project to JavaFX
I have a 4 years old project which is written in Swing + SwingX. Currently, it is still alive and still kicking.

However, as more GUI related feature requests coming in (For instance, a sortable tree table), I start to feel the difficulty in fulling the requests. This is true especially since there isn't any active development going around SwingX project.

Also, I can hardly find any good, yet actively maintained/ developed/ evolving GUI Java framework.

I was wondering, do any of the Swing developers feel the same thing? Have you start to migrate your Swing project to a much more active developed GUI framework, like JavaFX?

答:
I have been doing a lot of JavaFX now and I prefer it over Swing. The Scene Graph structure is different to what you're used to with Swing, but it provides so much improvements. The API is fun to work with, it feels refreshing.

There's so much more you can do with it, multimedia, animation, web browsing. You can for example build a Google Maps application in a few lines of code, embedding html5 and javascript.

It is said to be included in the Java 8 runtime, which would mean as the definate replacement of Swing as the default ui framework

@Migration: You should start by isolating parts of you application that can be converted to JavaFX. Swing-JavaFX 2 interoperability is a big thing, you can use the javafx.embed.swing.JFXPanel to embed your JavaFX element. See swing-fx-interoperability. (For completeness you can also embed in SWT.)


答:
Some times CSS class names are generic and aren't specifically named. For example, what if you had

```<code><!--Code before-->

<!--Column one-->
<div class="center-bold">

    <!--Tons of lines-->

</div>
<!--End column-->
</code>```

Wouldn't it be nice to know what your starting? I surely wouldn't want to scroll all the way to the end to find out that the whole div was a column.

Body:
```<code> <body>
  <!-- wrapper -->
  <div id="wrapper">
   <!-- title -->
   <div id="title"><img src="title.png" alt="" /></div>

   <!-- form wrapper -->
   <div id="form_wrapper">

    <!-- form -->
    <form action="thankyou.php" method="POST">
     <!-- ... ... -->
    </form>
    <!-- /form -->
   </div>
   <!-- /form wrapper -->
  </div>
  <!-- /wrapper -->
 </body>
</code>```

I can almost understand the  at the end, because it's so far from the start of the tag/pair...  but seriously, what's the point of the opening comment lines?  I wouldn't ask the question if I didn't see this all the time.

I feel as if I'm missing something.  Maybe there's some unwritten best-practice involved, though I fail to comprehend what it could possibly be.  More than likely it's just obsessive-compulsive behavior.

How do you guys normally comment your markup, if at all?

Body:
Some times CSS class names are generic and aren't specifically named. For example, what if you had

<!--Code before-->

<!--Column one-->
<div class="center-bold">

    <!--Tons of lines-->

</div>
<!--End column-->

Wouldn't it be nice to know what your starting? I surely wouldn't want to scroll all the way to the end to find out that the whole div was a column.


答:
AGPL and GPLv3 were created to close the "GPL as a service" loop hole. If the code is licensed this way and you are going to use the web server in a commercial setting I would look elsewhere.

I am not a lawyer, etc.

Affero General Public License

That is the purpose of the AGPL, am I correct?

AGPL is the opposite of what you are assuming here.

Does this also apply to Javascript frameworks like KendoUI?

You cannot use KendoUI GLPv3 license unless your whole product that is using it is also GPL compatible.

In other words, merely loading a web sites content into my browser is not "conveying" or "distributing" that software.

In GPLv3 and AGPL it is conveying and distributing.

These questions come up time and time again. We can apply logic and reasoning to most of the products in question. Kendo UI has a commercial version of the product available and a GPLv3 version available. It stands to reason that they do not want you using their product in a commercial settings, i.e. a non GPL application, unless you pay for it.

They even spell it out on their web page:

This version is suitable for GPL-compatible open source projects only.

Title: What are the legal risks if any of using a GPL or AGPL Web Application Framework/CMS?

Body:
Tried to ask this on SO but was referred here...

Am I correct in saying that using a GPL'ed web application framework such as Composite C1 would NOT obligate a company to share the source code we write against said framework?

That is the purpose of the AGPL, am I correct?

Does this also apply to Javascript frameworks like KendoUI?

The GPL would require any changes that we make to the framework be made available to others if we were to offer it for download.

In other words, merely loading a web sites content into my browser is not "conveying" or "distributing" that software.

I have been arguing that we should avoid GPL web frameworks and now after researching I am pretty sure I am wrong but wanted to get other opinions?

Seth


问:
Is constantly looking for code examples a sign of a bad developer?
I am a CS student with several years of experience in C and C++, and for the last few years I've been constantly working with Java/Objective C doing app development and now I have switched to web development and am mainly focused on ruby on rails and I came to the realization that (as with app development , really) I reference other code way too much. I constantly Google functionality for lots of things I imagine I should be able to do from scratch and it's really cracked my confidence a bit.

Basic fundamentals are not an issue, I hate to use this as an example but I can run through javabat in both java/python at a sprint - obviously not an accomplishment and but what I mean to say is I have a strong base for the fundamentals I think?

I know what I need to use typically but reference syntax constantly. Would love some advice and input on this, as it has been holding me back pretty solidly in terms of looking for work in this field even though I'm finishing my degree. My main reason for asking is not really about employment, but more that I don't want to be the only guy at a hackathon not hammering out nonstop code and sitting there with 20 Google/github tabs open, and I have refrained from attending any due to a slight lack of confidence...

Is a person a bad developer by constantly looking to code examples for moderate to complex tasks?

答:
Well, I don't call myself a good programmer. But what I do is simple. If I don't know how to do something I actually look at some code / example around the Internet. Then after reading it, I try to rewrite it, optimize it and using the stuff that it suits best for the code I want.

Note: Reading code from Internet doesn't make you a bad developer. It is always good to look how other people do it, and you'll always learn something. But then, copying it blindly isn't good.


问:
I need help deciding between silverlight/silverlight out-of-browser/wpf
I'm in the initial planning phase of a re-write project and I'm deciding between silverlight/silverlight oob/wpf. TL;DR at the end.

It's a LOB app that handles leads/customers/appointment calendars. Not too complicated. I'm independently researching these options elsewhere, but I thought I'd ask around. Some rough initial requirements/foreseeable problems are:

I have to be able to call an exe on the system with commandline args (sip phone).

Makes SL a problem

The userbase is distributed and I want to limit the traffic that goes over the wire as much as possible and avoid some nasty concurrency issues

I can see this being a problem using WPF

Software deployment/updating has to be dead simple. Some users are highly non-technical (see: 70 years old, on a computer for the first time)

This isn't a huge problem now with the ClickOnce app we are replacing, and I have control over the machines that it gets used on. However, it's simpler for users if they don't even have to click the clickonce "Install" button. I don't know how this is handled with Silverlight OOB.

The company is planning a hard expansion in 12 months so hardware deployment should be fast/easy. The idea is to get an internet connection at a new location, plug in some computers and be able to work without the need for dedicated IT people or server setup.

Makes SL appealing

Integration with other services (financial software, asterix server) isn't an immediate goal, but it is an eventual goal to be part of the system. This is made much simpler/more efficient if a single service is setup to integrate with those secondary services and doesn't have to transfer all of that data over the wire

Makes SL appealing

Making multiple 'versions' is out the window. I don't know what it's like maintaining a silverlight + silverlight oob version (if there's even any problems)

Might make WPF a better option.

TL;DR: From my vantage point, a silverlight app makes the best sense for 90% of the users - the other 10% can't use it because they need to run an exe. Silverlight OOB might be a happy middleground but I don't know at the moment what the execution model for it is like (is there still a concept of server-side code? If so, that would possibly be ideal) and I don't know how deployment/updating works for it.

答:
Your analysis is very good.

The only other thing that I would mention is that not ALL of the framework is available to you in a Silverlight application.  That restriction MAY tilt your choice towards WPF, but you'll need to see how that restriction applies or not to your application needs.


问:
Can you program Android Apps in a functional language?
Can you program Android Apps in  a functional language?

I meant is it possible to program for Android in a language that was designed from the ground up to be functional? I'm aware that you can use the functional components of an OO or a procedural language to program in a functional style, I was asking whether it would be applicable to use one of the "functional languages" on Android.

答:
Yes. You can build Android apps in both Scala and Clojure. The question is would apps produced with these languages be up to "production" standards and I think right now the consensus answer is "not yet"

EDIT: Remember I wrote my response almost 3 years ago (as of today). I believe that both Scala and Clojure have come a long way in that time. Plus Kotlin is another good option for building Android apps with a functional language.


答:
I think there are many levels of software development proficiency. Just so, because there are also many levels of software development documentation proficiency. Frankly, these days, systems are orders of magnitude more complex than when I began programming computers in the mid 1980's.

Then, you had to know what you wanted the computer to do, and you had written documentation 6 inches thick telling you how the computer did certain more basic things. Putting what you wanted into a form the computer could take was a matter of knowing the contents of those books' indices, and a programming language (or two. Really, after learning four or five languages the others are just dialects.)

Today, that task requires knowing a language, knowing a system, knowing a paradigm, a programming model, and at least one API set, all of which are moving targets.

So, A person with a certain level of basic knowledge who asks around is not a good kind of programmer. He is the best kind of programmer, given today's environments and the disinterest firms like Microsoft have in actually applying any kind of rigor to their own fundamentals documentation. Most of their stuff is self-referential reference material and some very bad sample code. (Two cases in point I've encountered are "Windows Installer" and the API's for making WMV movie files.)

Because Microsoft, Google, and, to a lesser extent, Apple, all rely on "the community" to make up for that very real deficiency, asking around is not just important, it's vital. And being a person who can be asked and who can give solid answers and feedback in today's environment is just as vital. That's why sites such as the stackexchange.com sites are as helpful as they are.

So ask questions, (ask intelligently!) for samples, and respect the people who supply the answers, and doing so will not be seen as a sign of a "bad developer".

And one more thing: Supplying bad samples really is the sign of a bad developer. It makes the bad developers easier to spot, but also gums up the google searches. If you lack confidence in simple, straightforward, specific code samples, don't give 'em.

And, please, don't mock those who ask.


问:
Object oriented design importance
I started studying Object Oriented Design and Modelling using the this book by James Rumbaugh. It uses a tool called Object Modeling Technique (OMT). I have certain newbie questions. I searched the net, but couldn't get answers

The book is pretty old. Don't know why the school told me to learn this. I know OMT is a predecessor of the Unified Modeling Language (UML). So its a waste?

Whether the concepts change very much when we move from OMT to UML? I know OMT has Object, Dynamic and Functional Model. Wikipedia says UML is compatible with OMT and UML is a model too.

As per wikipedia the UML models are Static and Dynamic and they are represented by different diagrams like class, object, activity, sequence..... I couldn't find the equivalence of this in OMT.

I read that there are many object oriented development methods like OMT, Booch,.... Which one is used by Industry ?

Where could I get a comparison of different Object oriented development methods?

答:
UML is a much larger modeling language than is OMT--the former basically a superset of the latter.  Because of this, any book on UML is going to contain a lot of stuff that will probably be more confusing than useful to a novice.  However, the book on OMT is very focused on something anyone trying to describe objects probably needs to know, and so it's a pretty good choice for a class.

Moreover, Rumbaugh is basically the MAN for this stuff.  What he brought to Rational was the foundation for UML.  This is foundational stuff--not a waste at all.

Title: Object oriented design importance


答:
The book is pretty old. Don't know why the school told me to learn this.

Because your professor thinks it is a good one? Object orientation is not a brand-new concept. And the concept does not depend on such details like if you are drawing the cardinality of an aggregation by using a star or a circle. The OMT book is not mainly about the graphical notation, it is mainly about object oriented modeling, which is a concept independent from the notation.

Whether the concepts change very much when we move from OMT to UML.

Learning OMT first will be no waste of time, as others have pointed out, UML is more like a superset of OMT. For example, the class diagram notation in OMT and UML is very similar, I guess you will grasp the notation differences in an hour.

As per wikipedia the UML models are Static and Dynamic and they are
  represented by different diagrams like class, object, activity,
  sequence..... I couldn't find the equivalence of this in OMT.

UML has some more diagram types compared to OMT, that's true. But class diagrams are the most important ones, and the differences are small. Real-world use of dynamic models is relatively seldom compared to class diagrams.

I read that there are many object oriented development methods like
  OMT, Booch,.... Which one is used by Industry ?

In the software industry IMHO you will find 90% of the companies using object oriented programming languages (but almost no diagrams), 9% using UML class diagrams and 1% using some additional tools like other UML diagrams or data flow diagrams (just my personal experience, YMMV).

Where could I get a comparison of different Object oriented development methods?

Enter "comparison of different Object oriented development methods" into Google, and you will probably find this link.

Title: Object oriented design importance

Body:
I started studying Object Oriented Design and Modelling using the this book by James Rumbaugh. It uses a tool called Object Modeling Technique (OMT). I have certain newbie questions. I searched the net, but couldn't get answers

The book is pretty old. Don't know why the school told me to learn this. I know OMT is a predecessor of the Unified Modeling Language (UML). So its a waste?

Whether the concepts change very much when we move from OMT to UML? I know OMT has Object, Dynamic and Functional Model. Wikipedia says UML is compatible with OMT and UML is a model too.

As per wikipedia the UML models are Static and Dynamic and they are represented by different diagrams like class, object, activity, sequence..... I couldn't find the equivalence of this in OMT.

I read that there are many object oriented development methods like OMT, Booch,.... Which one is used by Industry ?

Where could I get a comparison of different Object oriented development methods?


问:
A measure of development speed
I've seen a lot of tests measuring execution speed of programming languages, but I've never found tests measuring development speed.

I've heard development speed is increased when working with dynamic languages, but is there any proof of that ? I'm not trying to say dynamic languages aren't efficient, but I'd kind of like to see the results of a scientific study, if such a thing exists.

Even better would be informations on maintenance facility. Are some languages easier to debug than others ?

EDIT : I'm mostly interested in the differences between two languages that are close in syntax. For example, I guess programming in C will usually be slower than programming in Java; but is programming in Java faster than programming in C# ?

答:
What is productivity? What is product, even? No one knows, mathematically speaking.

KLoC?

Cyclomatic complexity?

Function points?

I believe that you would have to look at the business level and run percentile comparisons with other programmers doing similar work, then measure the features delivered per programmer. Those are very sophisticated and subtle points to be able to statistically measure and retain meaning.

Title: A measure of development speed


问:
Are the criticisms against Dart valid?
According to this Wikipedia article, Microsoft, Apple, Mozilla, and others criticize Dart, a programming language Google introduced to work in web browsers, because they feel "it seems harmful (cf. VBScript in IE)".

But Dart also compiles to Javascript, so a web application written in Dart can run on any modern browser. So are their concerns valid? Can Dart really be a threat to the web's openness?

答:
Dart doesn't threaten the open web.

There isn't one browser dominating the market right now so web developers can't afford having their site work well in one browser only. Even if Chrome has an optimized Dart VM it wouldn't make sense for a website to depend on it given the current browser landscape.

I don't see Dart being adopted outright by other browser vendors but it may have an impact on future web standards. For instance if JavaScript ever gets class based OO perhaps Dart can serve as an inspiration for the standard.

It's okay for vendors to introduce non-standard features once in a while. If Netscape and Microsoft didn't try a bunch of crazy things in the early days the web wouldn’t be the same today. (think JavaScript and XMLHttpRequest)

On a side note I don't think Dart is a particularly cool language. But it's still better than translating Java to JavaScript as Google is doing with GWT.

Title: Are the criticisms against Dart valid?


问:
How to use database adapters' cursors safely?
I started to use psycopg2 to connect my little python script to a PostgreSQL database few days ago. After some research I found that a lot of database connector, like psycopg, work using cursors.

I know what is a cursor and how to use it. But I still wonder if it's safe to use the same cursor all along the script life.

Is it safe?

Or would it be preferable to use a different cursor for each query?

答:
I believe creating a cursor starts a transaction in postgresql.

If that's the case (I don't know for sure) then:

INSERTS and UPDATES would not be reflected in other sessions because of transaction isolation

you may overflow the transaction buffer given enough commands


答:
It's clear from the answers already given that there's nothing wrong with researching your problem, instead of coding blindly. But the question that wasn't addressed, because you didn't ask it directly, is why are you feeling so insecure-- and what can you do about it? After all, lots of people google their way through problems and have plenty of confidence (even those who shouldn't...)

So, what to do? Maybe you just needed a few hundred pats on the back, which you just got, and can now code with confidence. But if that didn't do the job, I suggest you look into automated testing and Test-Driven Development. Nothing says "well done" like an "All tests passed" from your testing suite: When you get there, you know you've done it right.

You should also try challenging yourself a little: You say you're always looking up syntax you already know; so force yourself to write some code without looking up the syntax, and you'll (soon, if not immediately) find out that you're doing just fine after all.


问:
How should my local git workflow work?
At home, I have a server that is running some software (on a LAMP stack, but only accessible internally). I have another machine and a laptop that I both use for developing said software. What is the best workflow for me?

Should I have a repository on my local server, create a live branch, staging branch and development branch, then checkout the development branch from my laptop/development PC to work on, commit that back when I'm done, then merge the development branch with the staging branch for testing, before further merging to the live branch?

Would I simply checkout the production branch to my /www/var/ on my server?

Or am I thinking/going about this all wrong?

Thanks.

答:
Never checkout the production branch

Or more specifically, never work off the production branch (it is ok to check it out for testing and/or patching). And here is why. You never know when or if you would be asked to work on a different requirement/fix while you are already developing something else. The production branch should only be used for testing the code that is about to go live or to make quick fixes (fixes that have a development cycle much shorter than the avg. timespan between two check-ins to the production branch).

The first approach you have mentioned is the one I have observed most commonly in enterprise settings. Here are the advantages:

You can create as many different branches as you want for different features.

You do not have to lose your work should you decide to abandon your task temporarily or have to work on a different task for a short while.

Many developers have a habit of committing their changes to the branch so that they have a back-up (and to answer themselves "how the ... did I get here?" You obviously cannot take this approach with the production branch. If you use the Perforce system (I know you mentioned you are not) then you may be tempted to use the shelve feature but that does not get you out of situations I described in #1 and #2.

Some off topic advice on how to maintain dev. branches

I think it is a good practise to regularly merge the production branch to your dev. branch so that you do not have to undertake a massive merge task when you decide to merge your changes to the production branch. Another advantage of this practise is that if someone checks in a conflicting change to your changes to the production branch then you can find about that in your development cycle itself (assuming you test regularly while developing).

Another practise that you can follow to avoid messing up the production branch is to merge the production branch one final time with your dev. branch, test your dev. branch thoroughly to resolve/discover any conflicts (not just those that come up as line differences but even those that can come up as design level conflicts), and then merge your branch back to production.

Yet another good practise is to label the dev. branch with something that identifies the specific goal of that development task rather than just who owns that dev. branch (hence, dev_notificationEnhancement and not dev_monstertruck).

Title: How should my local git workflow work?


问:
Will hand-written assembly disappear?
Last week I was wondering, with compilers getting better and better at optimizing, will there be a point when there is no need for hand written assembly? Are there still specialized fields where the compilers aren't smart enough to produce code that rivals hand-written assembly?</p>

答:
Assembly or shellcode in general, is a most importance thing when you're writing a malware that exploit some security vulnerabilities (it's called worm). You must to write sequence of assembly instructions to bypass anti-virus. Most of anti-virus use signature-base technique to detect malicious code. Because of that, you cannot reuse old shellcode.
It's funny to write some line of assembly codes and made it work for some reasons :)</p>

Title: Will hand-written assembly disappear?


答:
If you don't check NULL value, specially, if that is a pointer to a struct, you maybe met a security vulnerability - NULL pointer dereference. NULL pointer dereference can be lead to some other serious security vulnerabilities such as buffer overflow, race condition ... that can be allow attacker take control of you computer.

Many software vendor like Microsoft, Oracle, Adobe, Apple ... release software patch to fix these security vulnerabilities. I think you should check NULL value of each pointer :)

Title: What does it mean to do a "null check" in C or C++?

Body:
I have been learning C++ and I am having a hard time understanding null. In particular, the tutorials I have read mention doing a "null check", but I am not sure what that means or why it's necessary.

What exactly is null?

What does it mean to "check for null"?

Do I always need to check for null?

Any code examples would be much appreciated.


问:
Product agnostic book on Message Queues?
Are there any recommendations for book(s) that are largely agnostic (with examples of MQ implementations is fine) on vendor but go to great details on the architecture, management, nomenclature, atomicity, durability, patterns, and logical deployments on Message Queue systems?

Surely there are enough shared concepts between MQ Series, MSMQ, SysV IPC (OK, that might be stretching it), RabbitMQ, &c &c?

答: I think the book you are looking for would be a valuable resource but in my experience I've only ever seen books available as they apply to one vendor or another.  I've had a lot of experience with IBM MQ and a fair amount with MSMQ and have looked for references from time to time but have never come across what you are looking for.  I'll be interested to see if anyone else has a different experience.</p>


问:
What are the arguments against parsing the Cthulhu way?
I have been assigned the task of implementing a Domain Specific Language for a tool that may become quite important for the company. The language is simple but not trivial, it already allows nested loops, string concatenation, etc. and it is practically sure that other constructs will be added as the project advances.

I know by experience that writing a lexer/parser by hand -unless the grammar is trivial- is a time consuming and error prone process. So I was left with two options: a parser generator à la yacc or a combinator library like Parsec. The former was good as well but I picked the latter for various reasons, and implemented the solution in a functional language.

The result is pretty spectacular to my eyes, the code is very concise, elegant and readable/fluent. I concede it may look a bit weird if you never programmed in anything other than java/c#, but then this would be true of anything not written in java/c#.

At some point however, I've been literally attacked by a co-worker. After a quick glance at my screen he declared that the code is uncomprehensible and that I should not reinvent parsing but just use a stack and String.Split like everybody does. He made a lot of noise, and I could not convince him, partially because I've been taken by surprise and had no clear explanation, partially because his opinion was immutable (no pun intended). I even offered to explain him the language, but to no avail.

I'm positive the discussion is going to re-surface in front of management, so I'm preparing some solid arguments.

These are the first few reasons that come to my mind to avoid a String.Split-based solution:

you need lot of ifs to handle special cases and things quickly spiral out of control

lots of hardcoded array indexes makes maintenance painful

extremely difficult to handle things like a function call as a method argument (ex. add( (add a, b), c)

very difficult to provide meaningful error messages in case of syntax errors (very likely to happen)

I'm all for simplicity, clarity and avoiding unnecessary smart-cryptic stuff, but I also believe it's a mistake to dumb down every part of the codebase so that even a burger flipper can understand it. It's the same argument I hear for not using interfaces, not adopting separation of concerns, copying-pasting code around, etc. A minimum of technical competence and willingness to learn is required to work on a software project after all. (I won't use this argument as it will probably sound offensive, and starting a war is not going to help anybody)

What are your favorite arguments against parsing the Cthulhu way?*

*of course if you can convince me he's right I'll be perfectly happy as well

答:
I'll be brief:

Parsing the Cthulhu way is hard. That's the simplest and most convincing argument against it.

It can do the trick for simple languages; say, regular languages. It's probably won't be easier than a regular expression, though.

It can also do the trick for a bit more complex languages.

However, I'd like to see a Cthulhu parser for any language with nesting, or just "significantly stateful" - mathematical expressions, or your example (nested function calls).

Imagine what would happen if someone tried to cthulhu a parser for such (non-trivial context-free) language. Provided he's smart enough to write a correct parser, I'd bet that during coding he would "discover" first tokenizaton, and then recursive descent parsing - in some form.

After that, the thing's simple: "Hey look, you've written something that's called a recursive descent parser! Do you know that it can be generated automatically from a simple grammar description, just like regular expressions?

Long story short:

The only thing that can stop somebody from using the civilised approach   is their ignorance of it.

ContentLicense: CC BY-SA 4.0


答:
Developers are not born “great,” but greatness does not automatically
  come with experience. Conversely, lack of experience does not make a
  developer “bad.” The difference between a great developer and a bad
  developer is not in their domain knowledge, but their methodology. The
  distinguishing mark of a great developer is that he codes consciously.
  Put another way, a good developer always knows why he is doing
  something. From the perspective of personal ethics, this requires
  intellectual courage and integrity.

It is so important to take some time and get to understand the basics, more complex things pretty much build on top of that. If there is no foundation in understanding the language and what is going on behind the scenes, coding will be simply hacking…