问:
Alternativates to HTML Help
We currently use a system called AsciiDoc which allows us to create documentation in a simple text markup. From that we can generate multiple output formats. We only make use of the pdf output and chm output formats.

I was wondering if there was an alternative to chm? What I am looking for is something that can be used off-line (this is important because quite a few of our users are in very remote places) with our software. It should have an index (it can be as simple as an html page with hyperlinked terms), it should be searchable and it should have a mechanism that allows specific entries to be called up from the code (similar to context sensitive help).

The two things that are against PDF in this case is:

Context sensitive help isn't an option

Generally the document is rather large

PDF is more suitable to printed documentation than context sensitive help

What I would like is to use html. The only problem with html is that I can't seem to figure out how to automatically provide a keyword search (other than the browsers ctrl+f functionality - I would like something more apparent). I also can't seem to find a method to automatically generate a hyperlinked index of key words. Context sensitive help would be simple because of the section tags - I could simply pass the url of the page and section that I am interested into the default browser and that page should load up to the correct section.

My requirements sound an awful lot like chm - they do. I modeled my requirements off chm. The only reason I don't like chm is because of the way the code interacts with it using mapids and such. I would much rather use store a plain text list (that is automatically generated for me) that my code can use to access the context sensitive portion of the documentation.

I am envisioning a script that would go through the html output files and generate an index page that simply contains a list of keywords that it found. obviously there should be word exclusion mechanism to ignore words like: the, it, is, etc.. This part would be relatively easy to write. The second part would need a script of some sort to put together a database of keywords and their location within the html text. I think this would be the tricky part along with providing the search mechanism within the browser.

Any ideas on alternatives would be appreciated. I would love to use a wiki or set of static html pages hosted on a webserver somewhere, but we have a critical offline usage requirement. Simply placing the html on the local drive doesn't provide us with the search requirements that we need.

EDIT:

I design software that is used by the mining industry. A lot of mines are very remote and do not have access to the internet in any meaningful way. There is nothing wrong with pdf or html or chm (except that it is getting old). If I could display a pdf file at the correct location (i.e. context sensitive help) I would use it. I am almost tempted to write my own - basically it would be a portable wiki. Speaking of that, if you suggest portable wiki - you have to think of the end user which may have no experience in using such tools. It has to be dead simple. That was the beauty of chm, it is a pain to work with but the end users like it.

答: The creators of RoboHelp went on to other things, and have come back around to make a better alternative.  Check out MadCap's Flare - it supports a variety of output formats, generates an index, and supplies a search function that operates locally (via JavaScript).</p>

ContentLicense: CC BY-SA 4.0

Title: Alternativates to HTML Help


问:
University teaches DOS-style C++, how to deal with it
I had been programming for many years but wanted a diploma to make myself more employable. Having already been through university once, I didn't choose a full 5 year computer science major but a shorter, more practically-oriented software engineering program.

I expected that it might focus more on concrete skills than on theory, but still had this idea that universities and professors like things to be correct, formal, academic. It's still science, right? Wrong - I was surprised by how sloppy many IT courses were.

In an introductory course on C++ we were tested on clichés like "why are globals bad" and "why are constants good", after just writing 1-2 programs. Random anecdotes without proper context. Handouts contained system(pause/cls), getch and headers like conio.h and iodos.h. One of the tasks was to print "ASCII characters" from 32 to 255, with a screenshot showing such a table printed using the Windows-1252 code page, but without mentioning encoding at all.

Question: when a university/professor seems to be using inferior and/or outdated tools and methods, and the content being taught is borderline incorrect, how do you deal with it constructively and respectfully, if at all?

Some answers point out that you should look beyond the programming since it is just a tool for learning about topics such as data structures and algorithms. I agree with this idea, but in this case there wasn't really any such plan behind the poor style. Most courses would simply teach another "tool" without much background theory or any "big picture". It often felt like they were quickly put together just for the sake of offering such a course.

I stuck with it and finally graduated. Quality remained pretty low throughout (with a few great exceptions), and several other students have been complaining about it. As expected I have learned much more from personal projects and part-time jobs than from school, however the process of finishing school and the label "software student" seem mysteriously useful in themselves!

答:
I thought a lot of the answers to this question were disappointing. They went back to the tired old argument about CS vs Programming etc. That may be so, but it sounds to me like the course the OP is on isn't teaching either.

I was in the situation of having already worked as a programmer, and studied quite a bit by myself, before studying CS part-time at college. I shopped around carefully, but generally found the curriculum to be a waste of time. Also they wouldn't let me skip courses despite already having professional experience in the area.

In my experience a significant proportion of professors are pretty lazy and using an outdated curriculum. Honestly it sounds like you are wasting your time. I question even whether completing the diploma will help you find a job.

I doubt you can do much to change things about your course. You can either supplement it with study by yourself. Or just forget the whole thing, and study CS independently, and do some industry certifications as well.

I should add that I have no idea about the value of the diploma in your country's job market. If the diploma itself is valuable despite the content, then you may just have to put up with a curriculum that is somewhat lacking.

OwnerDisplayName: gaidal

ContentLicense: CC BY-SA 3.0


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
I had a teacher that would tell students who were getting ahead of themselves this:

You don't know what you don't know

I can't say for sure if it's his quote or something he picked up from somewhere else.

LastEditorDisplayName: Roger Pate

ContentLicense: CC BY-SA 2.5


问:
What would truly happen if java.lang.String weren't final?
I'm a long time Java developer and finally, after majoring, I have time to study it decently in order to take the certification exam... One thing that has always bothered me is String being "final". I do understand it when a read about the security issues and related stuff... But, seriously, does anyone have a true example of that?

For instance, what would happen if String weren't final? Like it's not in Ruby. I haven't heard any complaints coming from the Ruby community... And I'm aware of the StringUtils and related classes that you have to either implement yourself or search over the web to just implement that behavior (4 lines of code) you're willing to.

答:
There's another reason why Java's String class needs to be final: it is important for security in some scenarios.  If the String class weren't final, the following code would be vulnerable to subtle attacks by a malicious caller:

```<code> public String makeSafeLink(String url, String text) {
     if (!url.startsWith("http:") && !url.startsWith("https:"))
         throw SecurityException("only http/https URLs are allowed");
     return "<a href=\"" + escape(url) + "\">" + escape(text) + "</a>";
 }
</code>```

The attack: a malicious caller could create a subclass of String, EvilString, where EvilString.startsWith() always returns true but where the value of EvilString is something evil (e.g., javascript:alert('xss')).  Due to the subclassing, this would evade the security check.  This attack is known as a time-of-check-to-time-of-use (TOCTTOU) vulnerability: between the time when the check is done (that the url starts with http/https) and the time when the value is used (to construct the html snippet), the effective value can change.  If String wasn't final, then TOCTTOU risks would be pervasive.

So if String is not final, it becomes tricky to write secure code if you can't trust your caller.  Of course, that's exactly the position that the Java libraries are in: they might be invoked by untrusted applets, so they don't dare trust their caller.  This means that it would be unreasonably tricky to write secure library code, if String weren't final.

Body:
There's another reason why Java's String class needs to be final: it is important for security in some scenarios.  If the String class weren't final, the following code would be vulnerable to subtle attacks by a malicious caller:

 public String makeSafeLink(String url, String text) {
     if (!url.startsWith("http:") && !url.startsWith("https:"))
         throw SecurityException("only http/https URLs are allowed");
     return "<a href=\"" + escape(url) + "\">" + escape(text) + "</a>";
 }

The attack: a malicious caller could create a subclass of String, EvilString, where EvilString.startsWith() always returns true but where the value of EvilString is something evil (e.g., javascript:alert('xss')).  Due to the subclassing, this would evade the security check.  This attack is known as a time-of-check-to-time-of-use (TOCTTOU) vulnerability: between the time when the check is done (that the url starts with http/https) and the time when the value is used (to construct the html snippet), the effective value can change.  If String wasn't final, then TOCTTOU risks would be pervasive.

So if String is not final, it becomes tricky to write secure code if you can't trust your caller.  Of course, that's exactly the position that the Java libraries are in: they might be invoked by untrusted applets, so they don't dare trust their caller.  This means that it would be unreasonably tricky to write secure library code, if String weren't final.


问:
How can I teach a bright person, with no programming experience, how to program?
I have been asked to take a person in our IT department who has no programming experience but is a smart and capable person and help him move into programming at lets say an entry level developer supporting existing .Net applications. I definitely believe this person can do it but I am looking for the quickest way to get him to speed. I have a bunch of ideas but wanted to see what other people thought. I know this is going to also be highly dependent on how he learns, but I am talking in general.

So the question: What do you think are the best ways to get a non-developer up to speed quickly on development (.Net in this case)?

答:
Pair programming.  Let them shadow you while you write your own code - any code.  Within hours, then have them enter your code in for you, while you tell them what to do, keystroke by keystroke even if necessary.  Answer a few of their questions, but not so much so that you get slowed down by much - just let them soak it all in.  They'll also find your typos and more of your bugs than you might think.  Within a few days, they'll be able to start 'navigating' telling you what code to enter for tasks similar to ones they've seen before.

I learned much of what I know as a developer this way within a month, and have taught several other new developers this way, one of whom was able to take over for me as the lead developer at a startup after several months.  When we first started working together, he hadn't ever written a single line of code.


答:
I know a lot of people have been talking about languages and books for those languages. I differ.

Programming is about learning to think analytically. First and foremost the person should be able to think and come up with the algo on a piece of paper for what the problem is. You have to guide them so that they get the right thinking technique.

Next comes the fundamentals of the language. Get them started on the language of choice. Give a problem to program.

After this first cut is over get them to do the CS fundamentals and the Design Patterns.

Now get them to reprogram the earlier problem with these new concepts.

Title: How can I teach a bright person, with no programming experience, how to program?

Body:
I have been asked to take a person in our IT department who has no programming experience but is a smart and capable person and help him move into programming at lets say an entry level developer supporting existing .Net applications. I definitely believe this person can do it but I am looking for the quickest way to get him to speed. I have a bunch of ideas but wanted to see what other people thought. I know this is going to also be highly dependent on how he learns, but I am talking in general.

So the question: What do you think are the best ways to get a non-developer up to speed quickly on development (.Net in this case)?


问:
Is it ethical to duplicate user licenses if the same person is going to be using it?
I was talking with someone today and this discussion came up.

Suppose you purchase some software and X user licenses for it. You then want to install another instance of the software, however the company tells you that you need to buy another X licenses to use the 2nd installation. Is it ethical to duplicate the licenses since the same X users are going to be using them? (the security on the program we were talking about is not very good)

EDIT
Licenses are per-concurrent-user. In this situation users would (generally) not be logged into both installations at once. Regardless, we would keep the number of users logged in between the two installations limited to the number of licenses we purchased.

答:
I use a commercial source control system and the need arose to have multiple installations but naturally we didn't want to buy (and separately manage) a ton of licenses between servers.  Contacting the vendor, it turns out that they respectfully handle this fact and will give those who ask a "free" set of licenses for the second server as long as all of the users are properly licensed on the first.

In other words, why are you asking this question here instead of contacting the application vendor?


答:
Give him a good ide (visual studios, express is still good). Teach him the common 60% of syntax (leave out yield, linq, enums, attributes, etc, do teach classes, virtual and override). Spend time on the debugger (especially callstack). Then tell him to google "msdn functionanme" whenever he needs help and that should get him off to a quick start.

Also teach him to never catch and swallow an exception. Tell him he must rethrow or log it!

Bonus: teach him how to serialize json data so he can easily read/write to a file. A db is overkill and too much to learn and you dont want to have him writing custom file formats although i may let one entry per line type of file pass to save/load an string array as acceptable.


答:
What I am looking for is something that can be used off-line (this is important because quite a few of our users are in very remote places) with our software.

We use RoboHelp at my company and we good luck making the help files available offline as we often have users going from areas with network access to areas without.

It should be searchable and it should have a mechanism that allows specific entries to be called up

We use some pages in RoboHelp to explain the use of certain fields on a screen. We are able to have pop-ups for those fields that appear after a click. RoboHelp also has a very nice search ability and auto-generated index. I've always had good luck searching with it. This might not be a huge concern for you, but we are able to have anyone update the documentation because RoboHelp is a fairly easy program to use.

Title: Alternativates to HTML Help

Body:
We currently use a system called AsciiDoc which allows us to create documentation in a simple text markup. From that we can generate multiple output formats. We only make use of the pdf output and chm output formats.

I was wondering if there was an alternative to chm? What I am looking for is something that can be used off-line (this is important because quite a few of our users are in very remote places) with our software. It should have an index (it can be as simple as an html page with hyperlinked terms), it should be searchable and it should have a mechanism that allows specific entries to be called up from the code (similar to context sensitive help).

The two things that are against PDF in this case is:

Context sensitive help isn't an option

Generally the document is rather large

PDF is more suitable to printed documentation than context sensitive help

What I would like is to use html. The only problem with html is that I can't seem to figure out how to automatically provide a keyword search (other than the browsers ctrl+f functionality - I would like something more apparent). I also can't seem to find a method to automatically generate a hyperlinked index of key words. Context sensitive help would be simple because of the section tags - I could simply pass the url of the page and section that I am interested into the default browser and that page should load up to the correct section.

My requirements sound an awful lot like chm - they do. I modeled my requirements off chm. The only reason I don't like chm is because of the way the code interacts with it using mapids and such. I would much rather use store a plain text list (that is automatically generated for me) that my code can use to access the context sensitive portion of the documentation.

I am envisioning a script that would go through the html output files and generate an index page that simply contains a list of keywords that it found. obviously there should be word exclusion mechanism to ignore words like: the, it, is, etc.. This part would be relatively easy to write. The second part would need a script of some sort to put together a database of keywords and their location within the html text. I think this would be the tricky part along with providing the search mechanism within the browser.

Any ideas on alternatives would be appreciated. I would love to use a wiki or set of static html pages hosted on a webserver somewhere, but we have a critical offline usage requirement. Simply placing the html on the local drive doesn't provide us with the search requirements that we need.

EDIT:

I design software that is used by the mining industry. A lot of mines are very remote and do not have access to the internet in any meaningful way. There is nothing wrong with pdf or html or chm (except that it is getting old). If I could display a pdf file at the correct location (i.e. context sensitive help) I would use it. I am almost tempted to write my own - basically it would be a portable wiki. Speaking of that, if you suggest portable wiki - you have to think of the end user which may have no experience in using such tools. It has to be dead simple. That was the beauty of chm, it is a pain to work with but the end users like it.


答:
Start him on the basics: variables, loops, while loops, for loops, arrays, teach him basics, printing to screen, doing some simple math. Move into methods and basic OOP, things like here's how to create a class, show him the why not just the how.

The language doesn't matter, but pick something you know and that is highly abstract (java, python etc...) that way he doesn't need to worry about things like memory management, pointers etc... Teach the basics of recursion, towers of hanio or recursively searching directories.

Learn to program is a good free resource on Ruby programming. Make it fun, easy and entertaining.


问:
What is the reporting function?
When dealing with an enterprise application, I often heard the requirement of "reporting function" "run reports", "generate reports", etc. What is it referring to?</p>

答:
Usually such requirements are about generating some sort of statistical report(s) from the data gathered in the DB. Such as

hourly/daily/monthly sales volume

most purchased goods during last day/week/...

most active users during last day/week/...

who modified a given contract, when and how

etc. The exact kind of report is largely dependent on the business domain and the type of application in question. Usually such reports are backed by (SQL) queries to the DB, but the source may also be server logs etc. The results may be generated as an Excel/CSV file, visualized as a diagram, etc.

Title: What is the reporting function?


答:
Reports in an enterprise application context usually refer to Business Intelligence reports. A broad definition of Business Intelligence, from Forester Research is:

Business intelligence (BI) is a set of methodologies, processes, architectures, and technologies that transform raw data into meaningful and useful information. It allows business users to make informed business decisions with real-time data that can put a company ahead of its competitors. Traditionally, core features like reporting and analytics have been the focus of BI technology choices, but as those features get commoditized, a whole new set of possibilities has emerged. Forrester's BI research shows that the technology is evolving and that enterprises on the cutting edge of these new trends can gain competitive advantage in their industries.

So, reporting mostly refers to the visualization and quering of Business Intelligence data. From a technical perspective, enterprise reporting usually involves (but is not limited to):

Data visualization,

Analytics (General, Statistical and Predictive),

Online analytical processing,

Data mining,

Process mining,

Benchmarking

Apart for a few common reports that are relevant for almost every business (basic statistics, common ERP / CRM operational reports), it's impossible to predict what a client requires when asking for reports, as every business and market has quite different operations and needs. Reports may range from simple charts to extremely complex multi-dimensional queries.

Title: What is the reporting function?

Body: When dealing with an enterprise application, I often heard the requirement of "reporting function" "run reports", "generate reports", etc. What is it referring to?</p>


答:
Give him some challenges and have him learn how to find resources to solve the problem himself.

If you can teach him how to find answers and be self-sufficient, he will naturally learn how to program well. Critical thinking and resourcefulness are two key skills for a programmer.

At the end of the day, passion/interest is definitely going to be a key factor in how successful they will be in learning it quickly. If he doesn't have or catch "the bug", it might be a slow and/or painful process. If he does catch the bug, he will be up late coding, off work hours, having the time of his life.


问:
OO best practices for C programs
"If you really want OO sugar - go use C++" -- was the immediate response I got from one of my friends when I asked this. I know two things are dead wrong here. First OO is NOT 'sugar', and second, C++ has NOT absorbed C.

We need to write a server in C (the front-end to which will be in Python), and so I am exploring better ways to manage large C programs.

Modeling a large system in terms of objects, and object interactions makes it more manageable, maintainable and extensible. But when you try to translate this model into C which does not bear objects (and everything else thereof), you're challenged with some important decisions.

Do you create a custom library to provide the OO abstractions your system needs? Things like objects, encapsulation, inheritance, polymorphism, exceptions, pub/sub (events/signals), namespaces, introspection, etc. (for example GObject or COS).

Or, you just use the basic C constructs (struct and functions) to approximate all your object classes (and other abstractions) in ad-hoc ways. (for example, some of the answers to this question on SO)

The first approach gives you a structured way to implement your entire model in C. But it also adds a layer of complexity that you have to maintain. (Remember, complexity was what we wanted to reduce by using objects in the first place).

I don't know about the second approach, and how effective it is at approximating all the abstractions you might require.

So, my simple questions is: What are the best practices in realizing an object oriented design in C. Remember I am not asking HOW to do it. This and this questions talk about it, and there's even a book on this. What I am more interested in are some realistic advice/examples that address the real issues that show up when dong this.

Note: please don't advice why C shouldn't be used in favor of C++. We've gone well past that stage.

答:
First off, unless this is homework or there is no C++ compiler for the target device I don't think you do have to use C, you can provide a C interface with C linkage from C++ easily enough.

Secondly, I'd look at how much you will rely on polymorphism and exceptions and the other features the frameworks can provide, if it's not much simple structs with related functions will be much easier than a fully featured framework, if a significant portion of your design needs them then bite the bullet and use a framework so you don't have to implement the features yourself.

If you don't really have a design yet to make the decision from then do a spike and see what the code tells you.

lastly it doesn't have to be a one or other choice (though if you go framework from the start you porbably may as well stick with it), it should be possible to start with simple structs for the simple parts and only add in libraries as needed.

EDIT: So its a decision by management right lets ignore the first point then.

Title: OO best practices for C programs


答:
GObject does not really hide any complexity and introduces some complexity of it's own. I would say that the ad-hoc thing is easier than GObject unless you need the advanced GObject stuff like signals or the interface machinery.

The thing is slightly different with COS since that comes with a preprocessor that extends the C syntax with some OO constructs. There is a similar preprocessor for GObject, the G Object Builder.

You could also try the Vala programming language, which is full high level language that compiles to C and in a way that allows using Vala libraries from plain C code. It can use either GObject, it's own object framework or the ad-hoc way (with limited features).

Title: OO best practices for C programs

Body:
"If you really want OO sugar - go use C++" -- was the immediate response I got from one of my friends when I asked this. I know two things are dead wrong here. First OO is NOT 'sugar', and second, C++ has NOT absorbed C.

We need to write a server in C (the front-end to which will be in Python), and so I am exploring better ways to manage large C programs.

Modeling a large system in terms of objects, and object interactions makes it more manageable, maintainable and extensible. But when you try to translate this model into C which does not bear objects (and everything else thereof), you're challenged with some important decisions.

Do you create a custom library to provide the OO abstractions your system needs? Things like objects, encapsulation, inheritance, polymorphism, exceptions, pub/sub (events/signals), namespaces, introspection, etc. (for example GObject or COS).

Or, you just use the basic C constructs (struct and functions) to approximate all your object classes (and other abstractions) in ad-hoc ways. (for example, some of the answers to this question on SO)

The first approach gives you a structured way to implement your entire model in C. But it also adds a layer of complexity that you have to maintain. (Remember, complexity was what we wanted to reduce by using objects in the first place).

I don't know about the second approach, and how effective it is at approximating all the abstractions you might require.

So, my simple questions is: What are the best practices in realizing an object oriented design in C. Remember I am not asking HOW to do it. This and this questions talk about it, and there's even a book on this. What I am more interested in are some realistic advice/examples that address the real issues that show up when dong this.

Note: please don't advice why C shouldn't be used in favor of C++. We've gone well past that stage.


答:
I think you need to differentiate OO and C++ in this discussion.

Implementing objects is possible in C, and it's pretty easy - just create structures with function pointers. That's your "second approach", and I would go with it. Another option would be to not use function pointers in the struct, but rather pass the struct of data to the functions in direct calls, as a "context" pointer. That's better, IMHO, as it is more readable, more easily traceable, and allows adding functions without changing the struct (easy on inheritance if no data is added). That's in fact how C++ usually implements the this pointer.

Polymorphism becomes more complicated because there's no built-in inheritance and abstraction support, so you'll have to either include the parent struct in your child class, or do a lot of copy pastes, either of those options is frankly horrible, even though technically simple. Enormous amount of bugs waiting to happen.

Virtual functions can easily be achieved through function pointers pointing to different functions as required, again - very bug prone when done manually, a lot of tedious work on initializing those pointers correctly.

As to namespaces, exceptions, templates, etc - I think that if you're limited to C - you should just give up on those. I've worked on writing OO in C, wouldn't do it if I have a choice (at that place of work I literally fought my way into introducing C++, and the managers were "surprised" to how easy it was to integrate it with the rest of the C modules at the end.).

Goes without saying that if you can use C++ - use C++. There's no real reason not to.

Title: OO best practices for C programs


答:
Reporting is the activity of applying transformations to stored data so that the end user can get information or satisfy business needs such as invoicing, control, planning, etc.

Some examples of basic reports:

In a retail system, you get a receipt after making a payment. This recipt is a type of report.

In a retail system, the manager may want to pull all the items that will expire in a given data.

In an HR system, an HR manager may want to list people who's salaries > 100K

Stock items shortage report, shewing items that reached re-order level and must be ordered to satisfy expected customer demand.

System failure analysis reports showing time of system failure and associated messages

In a banking system, a monthly statement is a report.

The above reports are referred to as 'operational reports' - They are built and used to control the operation of day-to-day business operations. Another type of reports exist to better control the business and make decisions about performance of the business in general and in particular against per-defined KPIs. Such reports pull information from one or more system and produce a 360-view to the management about a subject area or more.  These reports are usually refereed to as Business Intelligence Reports For example:

Inventory across Regions, states, stores

Sales of different goods across Regions, states, stores

Customer consumption of goods from organization

There are still more types of reports such as Data Mining reports, I will leave that for you to research if you want.

The report may be as simple as a list or as an aggrigated format with controls and calculations. See for example

Group View Report

Reports, as you can imagine, may be consumed by customer, end-user, analyst, manager, etc. The business analyst defines the suitability of each type of report to each type of users. Managers usually use high level views of information structured in an appealing visual display commonly referred to as Dash Boards.

See this for example:

Dash-1

Dash-3

Dash-2

Reports are not only text. A report can display information in both text and graphical format as a chart or maps.

Reports can be the result of a simple query or the result of a series of integration operations (as is the case of large BI and data warehousing environments).

Tools exist to generate reports using either programming language or specific reporting tools or languages.

End-user tools such as Excel can be used for reporting. In fact Excel provides an advanced type of reporting called pivot tables reports.

See: Pivot Tables in Excel

More advanced tools exist such as:

Advanced Analytics

Reporting can be performed in an on-linen environment or in batch. The subject is so wide to cover here, but I think you get the picture.

Title: What is the reporting function?


问:
How do you dive into large code bases?
What tools and techniques do you use for exploring and learning an unknown code base?

I am thinking of tools like grep, ctags, unit-tests, functional test, class-diagram generators, call graphs, code metrics like sloccount, and so on. I'd be interested in your experiences, the helpers you used or wrote yourself and the size of the code base with which you worked.

I realize that becoming acquainted with a code base is a process that happens over time, and familiarity can mean anything from "I'm able to summarize the code" to "I can refactor and shrink it to 30% of the size". But how to even begin?

答:
I would say to start with documentation, etc., but in my experience, the depth of documentation and local knowledge is often inversely proportional to the age, size and complexity of a system.

That being said, I usually try to identify a couple of functional threads.  By functional I mean stuff like logging in, pulling down a list of customers, etc.  If the patterns are consistent at all, one thread should give you a nice, not necessarily complete, cross-section of the system.  The best way to determine if the patterns are consistent is to analyze a handful of threads.

I think this goes without saying but, in my opinion, it's better to understand the system from a functional perspective rather than from a technical perspective.  I generally don't worry too much about the tools that are being used (ORMs, logging libraries, etc.) and focus more on the patterns (MVP, etc.) that are being used.  In my experience, tools are generally more fluid that patterns.

Title: How do you dive into large code bases?


问:
code contracts/asserts: what with duplicate checks?
I'm a huge fan of writing asserts, contracts or whatever type of checks available in the language I'm using. One thing that bothers me a bit is that I'm not sure what the common practice is for dealing with duplicate checks.

Example situation: I first write the following function

```<code>void DoSomething( object obj )
{
  Contract.Requires<ArgumentNullException>( obj != null );
  //code using obj
}
</code>```

then a few hours later I write another function that calls the first one. As everything is still fresh in memory, I decide not to duplicate the contract, since I know that DoSomething wil check for a null object already:

```<code>void DoSomethingElse( object obj )
{
  //no Requires here: DoSomething will do that already
  DoSomething( obj );
  //code using obj
}
</code>```

The obvious problem: DoSomethingElse now depends on DoSomething for verifying that obj is not null. So should DoSomething ever decide not to check anymore, or if I decide to use another function obj might not be checked anymore. Which leads me to writing this implementation after all:

```<code>void DoSomethingElse( object obj )
{
  Contract.Requires<ArgumentNullException>( obj != null );
  DoSomething( obj );
  //code using obj
}
</code>```

Always safe, no worries, except that if the situation grows the same object might be checked a number of times and it's a form of duplication and we all know that's not so good.

What is the most common practice for situation like these?

答:
Personally I would check for null in any function that will fail if it gets a null, and not in any function which won't.

So in your example above, if doSomethingElse() doesn't need to dereference obj then I wouldn't check obj for null there.

If DoSomething() does dereference obj then it should check for null.

If both functions dereference it then they should both check.  So if DoSomethingElse dereferences obj then it should check for null, but DoSomething should also still check for null as it may be called from another path.

This way you can leave the code fairly clean and still guarantee that checks are in the correct place.


答:
From my answer to How should I structure complex projects in C (not OO but about managing complexity in C):

The key is modularity. This is easier to design, implement, compile
  and maintain.

Identify modules in your app, like classes in an OO app.

Separate interface and implementation for each module, put in interface only what is needed by other modules. Remember that there is
  no namespace in C, so you have to make everything in your interfaces
  unique (e.g., with a prefix).

Hide global variables in implementation and use accessor functions for read/write.

Don't think in terms of inheritance, but in terms of composition. As a general rule, don't try to mimic C++ in C, this would be very
  difficult to read and maintain.

From my answer to What are the typical naming conventions for OO C public and private functions (I think this is a best practice):

The convention I use is:

Public function (in header file):

```<code>struct Classname;
Classname_functionname(struct Classname * me, other args...);
</code>```

Private function (static in implementation file)

```<code>static functionname(struct Classname * me, other args...)
</code>```

Moreover, many UML tools are able to generate C code from UML diagrams. An open source one is Topcased.

Title: OO best practices for C programs

Body:
From my answer to How should I structure complex projects in C (not OO but about managing complexity in C):

The key is modularity. This is easier to design, implement, compile
  and maintain.

Identify modules in your app, like classes in an OO app.

Separate interface and implementation for each module, put in interface only what is needed by other modules. Remember that there is
  no namespace in C, so you have to make everything in your interfaces
  unique (e.g., with a prefix).

Hide global variables in implementation and use accessor functions for read/write.

Don't think in terms of inheritance, but in terms of composition. As a general rule, don't try to mimic C++ in C, this would be very
  difficult to read and maintain.

From my answer to What are the typical naming conventions for OO C public and private functions (I think this is a best practice):

The convention I use is:

Public function (in header file):

struct Classname;
Classname_functionname(struct Classname * me, other args...);

Private function (static in implementation file)

static functionname(struct Classname * me, other args...)

Moreover, many UML tools are able to generate C code from UML diagrams. An open source one is Topcased.


答:
Here are the basics of how to create object orientation in C

1. Creating Objects and Encapsulation

Usually - one creates an object like

object_instance = create_object_typex(parameter);

Methods can defined in one of the two ways here.

```<code>object_type_method_function(object_instance,parameter1)
OR
object_instance->method_function(object_instance_private_data,parameter1)
</code>```

Note that in most cases, object_instance (or object_instance_private_data) is returned is of type void *. The application cannot be reference individual members or functions of this.

Further to this each method uses these object_instance for subsequent method.

2. Polymorphism

We can use many functions and function pointers to override certain functionality in run time.

for example - all object_methods are defined as a function pointer which can be extended to public as well as private methods.

We can also apply function overloading in a limited sense, by way of using var_args  which is very similar to how variable number of arguments defined in printf. yes, this is not pretty as flexible in C++ - but this is closest way.

3. Defining inheritance

Defining inheritance is a bit tricky but one can do the following with structures.

```<code>typedef struct {
     int age,
     int sex,
} person;

typedef struct {
     person p,
     enum specialty s;
} doctor;

typedef struct {
     person p,
     enum subject s;
} engineer;

// use it like
engineer e1 = create_engineer();
get_person_age( (person *)e1);
</code>```

here the doctor and engineer is derived from person and it is possible to typecast it to higher level, say person.

Best example of this is used in GObject and derived objects from it.

4. Creating virtual classes
I am quoting a real life example by a library called libjpeg used by all browsers for jpeg decoding. It creates a virtual class called error_manager which the application can create concrete instance and supply back -

```<code>struct djpeg_dest_struct {
  /* start_output is called after jpeg_start_decompress finishes.
   * The color map will be ready at this time, if one is needed.
   */
  JMETHOD(void, start_output, (j_decompress_ptr cinfo,
                               djpeg_dest_ptr dinfo));
  /* Emit the specified number of pixel rows from the buffer. */
  JMETHOD(void, put_pixel_rows, (j_decompress_ptr cinfo,
                                 djpeg_dest_ptr dinfo,
                                 JDIMENSION rows_supplied));
  /* Finish up at the end of the image. */
  JMETHOD(void, finish_output, (j_decompress_ptr cinfo,
                                djpeg_dest_ptr dinfo));

  /* Target file spec; filled in by djpeg.c after object is created. */
  FILE * output_file;

  /* Output pixel-row buffer.  Created by module init or start_output.
   * Width is cinfo->output_width * cinfo->output_components;
   * height is buffer_height.
   */
  JSAMPARRAY buffer;
  JDIMENSION buffer_height;
};
</code>```

Note here that JMETHOD expands in a function pointer through a macro which needs to be loaded with right methods respectively.

I have tried to say so many things without too much individual explanations. But i hope people can try their own things. However, my intention is just to show how things map.

Also, there will be many arguments that this won't be exactly true property of the C++ equivalent. I know that OO in C -wont be that strict to its definition. But working like that one would understand some of the core principles.

Important thing is not that OO is as strict as in C++ and JAVA. It is that one can structurally organize the code with OO thinking in mind and operate it that way.

I would strongly recommend people to see the real design of libjpeg and following resources

a. Object oriented programming in C

b. this is a good place where people exchange ideas

c. and here is the full book

Title: OO best practices for C programs

Body:
Here are the basics of how to create object orientation in C

1. Creating Objects and Encapsulation

Usually - one creates an object like

object_instance = create_object_typex(parameter);

Methods can defined in one of the two ways here.

object_type_method_function(object_instance,parameter1)
OR
object_instance->method_function(object_instance_private_data,parameter1)

Note that in most cases, object_instance (or object_instance_private_data) is returned is of type void *. The application cannot be reference individual members or functions of this.

Further to this each method uses these object_instance for subsequent method.

2. Polymorphism

We can use many functions and function pointers to override certain functionality in run time.

for example - all object_methods are defined as a function pointer which can be extended to public as well as private methods.

We can also apply function overloading in a limited sense, by way of using var_args  which is very similar to how variable number of arguments defined in printf. yes, this is not pretty as flexible in C++ - but this is closest way.

3. Defining inheritance

Defining inheritance is a bit tricky but one can do the following with structures.

typedef struct {
     int age,
     int sex,
} person;

typedef struct {
     person p,
     enum specialty s;
} doctor;

typedef struct {
     person p,
     enum subject s;
} engineer;

// use it like
engineer e1 = create_engineer();
get_person_age( (person *)e1);

here the doctor and engineer is derived from person and it is possible to typecast it to higher level, say person.

Best example of this is used in GObject and derived objects from it.

4. Creating virtual classes
I am quoting a real life example by a library called libjpeg used by all browsers for jpeg decoding. It creates a virtual class called error_manager which the application can create concrete instance and supply back -

struct djpeg_dest_struct {
  /* start_output is called after jpeg_start_decompress finishes.
   * The color map will be ready at this time, if one is needed.
   */
  JMETHOD(void, start_output, (j_decompress_ptr cinfo,
                               djpeg_dest_ptr dinfo));
  /* Emit the specified number of pixel rows from the buffer. */
  JMETHOD(void, put_pixel_rows, (j_decompress_ptr cinfo,
                                 djpeg_dest_ptr dinfo,
                                 JDIMENSION rows_supplied));
  /* Finish up at the end of the image. */
  JMETHOD(void, finish_output, (j_decompress_ptr cinfo,
                                djpeg_dest_ptr dinfo));

  /* Target file spec; filled in by djpeg.c after object is created. */
  FILE * output_file;

  /* Output pixel-row buffer.  Created by module init or start_output.
   * Width is cinfo->output_width * cinfo->output_components;
   * height is buffer_height.
   */
  JSAMPARRAY buffer;
  JDIMENSION buffer_height;
};

Note here that JMETHOD expands in a function pointer through a macro which needs to be loaded with right methods respectively.

I have tried to say so many things without too much individual explanations. But i hope people can try their own things. However, my intention is just to show how things map.

Also, there will be many arguments that this won't be exactly true property of the C++ equivalent. I know that OO in C -wont be that strict to its definition. But working like that one would understand some of the core principles.

Important thing is not that OO is as strict as in C++ and JAVA. It is that one can structurally organize the code with OO thinking in mind and operate it that way.

I would strongly recommend people to see the real design of libjpeg and following resources

a. Object oriented programming in C

b. this is a good place where people exchange ideas

c. and here is the full book


答:
Borrowing some experience from the various Objective-C runtimes, writing a dynamic, polymorphic OO capability in C is not too hard (making it fast and easy to use, on the other hand, appears to still be ongoing after 25 years). However, if you implement an Objective-C style object capability without extending the language syntax then the code you end up with is quite messy:

every class is defined by a structure declaring its superclass, the interfaces it conforms to, the messages it implements (as a map of "selector", the message name, to "implementation", the function that provides the behaviour) and the class's instance variable layout.

every instance is defined by a structure which contains a pointer to its class, then its instance variables.

message sending is implemented (give or take some special cases) using a function that looks like objc_msgSend(object, selector, …). By knowing what class the object is an instance of, it can find the implementation matching the selector and thus execute the correct function.

That's all part of a general-purpose OO library designed to allow multiple developers to use and extend each other's classes, so could be overkill for your own project. I have often designed C projects as "static" class-oriented projects using structures and functions:
 - each class is the definition of a C structure specifying the ivar layout
 - each instance is just an instance of the corresponding structure
 - objects can't be "messaged", but method-like functions looking like MyClass_doSomething(struct MyClass *object, …) are defined. This makes things clearer in the code than the ObjC approach but has less flexibility.

Where to trade-off lies depends on your own project: it sounds though like other programmers won't be using your C interfaces so the choice comes down to internal preferences. Of course, if you decide you want something like the objc runtime library, then there are cross-platform objc runtime libraries that will service.

Title: OO best practices for C programs


问:
GIT branch model for derivative work
I'm planning on using Vincent Driessen's branching model which I found great for my current development. I think Vincent approach is very general to any development project but I'm finding it difficult to handle the following scenario.

I'm working on an application that will be branded to several customers, so each one of my bundles is a different branch that I rebase from develop branch each time a new build is going to be released. Each brand has its assets (images and text) and they do not conflict with changes in develop branch because in that branch I never touch the assets.

My question is, now that I'm planning on using it, how can I handle different versions based on the same code base but with different assets?

答:
I've skimmed over the article, so I can't be sure I got everything 100% correct, but here's my idea: can you simply edit your assets in the master branch? Or, if you're keeping your "branded branches", modify your assets only there. You can then simply merge the code from your develop, since you're not touching any assets there.

To be honest, if assets are the only problem here, I'd create a config file (or a database table if you have one) for your application which would tell it which assets to load dynamically. This would eliminate any "brand branches" and make it easy for you to maintain your assets easily.

Title: GIT branch model for derivative work


问:
Do any languages use =/= for the inequality operator?
Wikipedia says:

Not equal

The symbol used to denote inequation — when items are not equal — is a slashed equals sign "≠" (Unicode 2260).

Most programming languages, limiting themselves to the ASCII character set, use ~=, !=, /=, =/=, or <> to represent their boolean inequality operator.

All of these operators can be found in this table, apart from =/=. I can find this equals-slash-equals used as a way of formatting ≠ in plaintext but not in any programming language.

Has =/= been used as the inequality operator in any programming language?

答: In the long list of languages that don't use =/=, PROLOG uses X =\= Y as "the values X and Y are not equal", as opposed to the equality operator =:=. (Equality, not to be confused with the unification operator =!)


答:
Yes, it is in Erlang. =/= means exactly not equal to, that would be somewhat equivalent to !==.

See more subtle differences (such as =< instead of <=) here: http://www.erlang.org/doc/reference_manual/expressions.html#id198443

Title: Do any languages use =/= for the inequality operator?

Body:
Wikipedia says:

Not equal

The symbol used to denote inequation — when items are not equal — is a slashed equals sign "≠" (Unicode 2260).

Most programming languages, limiting themselves to the ASCII character set, use ~=, !=, /=, =/=, or <> to represent their boolean inequality operator.

All of these operators can be found in this table, apart from =/=. I can find this equals-slash-equals used as a way of formatting ≠ in plaintext but not in any programming language.

Has =/= been used as the inequality operator in any programming language?


问:
How can I charge money for open source targeted at individuals?
Most questions like this only seem to apply for big pieces of software for companies with money. I'm developing a small application targeted at individuals.

Informally speaking, I want to sell the application to users, but allow them to fix and modify it(but not redistribute).

Practically and legally speaking, how would I do this?

答:
IANAL, as usual and if you are seriously in the business of earning money this way, you should definitely hire a lawyer for this.

The basic idea is that you can do pretty much whatever you want in your license.

Normal proprietary licenses are one things: you may use it, but nothing else.

Open source licenses are the other end of the spectrum: you may use it, modify it, redistribute it (and sometimes some restrictions as well).

You can put your own license anywhere in that spectrum (and probably somewhere outside that spectrum as well). So it would be fine to write a license that says "you may use this, read the code, modify the code, but you must not re-distribute the code (modified or unmodified)".


答:
Why exactly do you want to prevent your clients from redistributing the software? A fear that you may miss out when they turn your software into a multi billion dollar cash cow?

If you're writing softwarte that's customised for the needs of an individual client, then this scenario is so unlikely it's not woth the time to worry about it.

Title: How can I charge money for open source targeted at individuals?

Body:
Most questions like this only seem to apply for big pieces of software for companies with money. I'm developing a small application targeted at individuals.

Informally speaking, I want to sell the application to users, but allow them to fix and modify it(but not redistribute).

Practically and legally speaking, how would I do this?


答:
I know this doesn't necessarily answer your question but none of us are lawyers so we are not qualified to give you legal advice on this.

Some viable alternatives that could be lucrative as well:

It may be easier to give the application for free and then charge for support or consultation work to larger clients.

If this doesn't make sense in your business model then you can always follow the RedHat JBoss model and have an open source Community edition but have a seperate but highly similar branch that is for your proprietary edition.

As a supplementary source of income to support, you can always open source the software but sell the documentation, manuals and books.  Good examples of successful open source projects that make good supplementary income on documentation, manuals and books are iText and Primefaces to name a few.


问:
When to use MVC
I'm building a site with PHP and a MySQL backend. But, I am currently not using any type of framework. Should I be using Model View Controller?</p>

答:
As an architecture, MVC focuses on splitting your project/webpage into multiple parts. This can make your life easier when you'll have to change something in the code or the user interface.

Rule of thumb, if you expect changes in specifications about your project especially when those changes affect the entire code, then go with the architecture that forces you to break up the code into tiny lego pieces.

Title: When to use MVC


问:
Does it make sense to license unit tests?
I am wondering if there are any benefits / risks of (not) putting a licence on test code which mostly consists of unit tests. What do you think?

I am particularly interested in licensing under (L)GPL, Apache, MIT and BSD.

EDIT: The assumption is that non-test code is already published under some licence, but test code is not, so the question is whether to publish it and if so whether to put the same licence on it.

答:
I'm surprised that no-one has mentioned this already, but if you don't attach a license to your code, whether it be product or test code, then others have no rights over the code.

Licensing code is about giving rights to others that they would not normally have. Your test code is automatically covered by copyright (in most countries around the world) even if you don't explicitly attach a copyright notice. Being copyrighted, other people cannot use, distribute or derive from that code.

By attaching a license to your test code, you give people the right to use, distribute and/or modify that code in accordance with the license terms.

I would recommend that you distribute your test code with your product code, under the same license. This is simplest for everyone. It also means that if people want to submit patches to you, then they can run your unit tests before they sent you a patch, which should help weeding out patches which break things.

OwnerDisplayName: leden


问:
Should I accept to write unsecure code if my employer requests me to do so?
My employer asked me to implement a feature that would require storing passwords in clear text in a database (or using an obscure encrypt/decrypt function stored in a binary, which is a bit better, but also insecure).

I replied that I was willing to implement such a feature, provided that customers were acknowledged of security implications when using it.

When discussing this problem with colleagues, someone told me that, as a software engineer, we are personally responsible (in the legal sense) for security problems that we introduce in our products. I looked into my contract, but did not found anything related to a similar case.

From a legal point of view, should I refuse to implement such a feature?
Is it true that my employer could take me to court if a customer experiences damage due to this feature, even if he was aware of security concerns as well?

EDIT: I understand this question can only be answered reliably from a lawyer. The same is true for licensing questions: people here give their understanding and their experience, sometimes after having consulted a lawyer, with no guarantee it applies in another jurisdiction. But licensing is explicitly accepted as a topic here, see What kind of questions can I ask here?. I believe other programmers may have the same issue, and other may have been confronted to this situation before, and may have consulted a lawyer for that.

答:
Personally, I've never heard of a software engineer, without a clause in the contract or other formal agreement, being held legally responsible for security problems in products they work on. From what I've read about laws and ethics in software engineering, the security requirements for a system are dictated by the requirements specification, which also refers to any legal, industry, or corporate requirements. When building a system, failure to meet security requirements is treated as a failure to complete the terms of the contract as the system was not built as specified. How the specific events unfold depends on the contracts between the engineer and the employer and the employer and the customer.

Laws also don't tell you what you should do, but what you can/can't do. You don't mention what industry that you are in, but some do have laws, regulations, and rules as to how to handle specific types of data - what has to be encrypted, minimum levels of encryption, requirements for managing/controlling access, and so forth. If your area (country, state) doesn't have rules about security, your industry doesn't have rules about security, and the software requirements don't call out security requirements or standards, it might be more of an ethical issue than a legal issue.

When it comes to ethical issues in software development, I subscribe to the Software Engineering Code of Ethics and Professional Practice. Ultimately, it's your call. However, I feel that storing passwords in plaintext or in a format that can be decrypted is unethical.


问:
Handling scripting in windows
I worked in Linux environment before and I have to work in windows XP for my current project. In linux, I enjoyed using script files for automating tasks(even smaller ones), and it did save me a lot of time.

I see windows command prompt is severely handicapped in terms of power and the number of commands available.

I came across Power shell, but I think it is a overkill , because I am not a windows admin or something.

Have you been in my situation before? Do you work on windows and automate tasks? Is there any place where I can learn them ?

答:
I'm a java developer working with windows xp boxes and for certain tasks, powershell is a clear winner, given the windows restraint, the same as you have.  I had to hit a web service api and was able to do so with just a few lines of code in powershell.

Being a beginner trying to learn it, I found PowerGUI which is a great tool.  It's a free IDE for PowerShell that has intellisense, which really helps!

Title: Handling scripting in windows


问:
Is "Computer Science != Software Engineering" an excuse to teach programming poorly?
We've all heard it; whenever there's a discussion about CS grads having poor development skills someone eventually says,

Computer science isn't software engineering.

The problem that I see is that programming and software development are taught in CS courses. They're just commonly taught poorly. If it's being taught, then why not teach it right the first time? *

So I would like to see what the opinions are on 2 questions:

Is the CS != SE argument a copout or excuse for not properly teaching programming skills.

Regardless of your answer to question 1; if you were in the almighty position of making such a decision: would you force an emphasis on proper teaching of programming in CS courses?

*. I have a suspicion, based on anecdotal evidence I obtained throughout my education, that most academics in the field haven't had to write code to be maintained and haven't maintained code, and as a result don't have the knowledge/skills to teach it effectively.

答:
Yes, this sounds like a cop-out to me, and a sign of CS's immaturity as an academic discipline.

An American Chemical Society accredited B.S. program requires you to have passed specific courses to demonstrate particular proficiencies in both theory (lecture classes) and practice (lab classes). At present, CS has nothing like that as far as I know.

One of my grad schol profs was a very ivory-tower theoretician whose office was never sullied with anything more physically chemical than a fishbowl with Magic Rocks, but when I was his TA for freshman chem, he also proved to be a quite competent bench chemist.

When I worked as an industrial paint chemist, they'd have laughed their heads off at the notion that I'd have a bachelor's and be incompetent in the lab. Of course the details of what I was doing in the lab were different than what I'd had in lab classes in school, but the principles were the same - we just used a paint mixer and a can, rather than a beaker and magnetic stirrer.

If one were to apply the same approach to CS, the details of what one might teach as practical software development skills for a CS/SE curriculum might vary from school to school, and over time. But it just sounds crazy to me that it's acceptable that somebody could get a degree in the field and not be competent at writing, debugging, and maintaining some kind of code. (Of course, that's how things actually are in many CS programs, but it's still crazy.)


答: Just conform to the development process of your project: if this feature is written in the requirement document, you shall implement it.</p>

Title: Should I accept to write unsecure code if my employer requests me to do so?

Body:
My employer asked me to implement a feature that would require storing passwords in clear text in a database (or using an obscure encrypt/decrypt function stored in a binary, which is a bit better, but also insecure).

I replied that I was willing to implement such a feature, provided that customers were acknowledged of security implications when using it.

When discussing this problem with colleagues, someone told me that, as a software engineer, we are personally responsible (in the legal sense) for security problems that we introduce in our products. I looked into my contract, but did not found anything related to a similar case.

From a legal point of view, should I refuse to implement such a feature?
Is it true that my employer could take me to court if a customer experiences damage due to this feature, even if he was aware of security concerns as well?

EDIT: I understand this question can only be answered reliably from a lawyer. The same is true for licensing questions: people here give their understanding and their experience, sometimes after having consulted a lawyer, with no guarantee it applies in another jurisdiction. But licensing is explicitly accepted as a topic here, see What kind of questions can I ask here?. I believe other programmers may have the same issue, and other may have been confronted to this situation before, and may have consulted a lawyer for that.


答:
Most open source license permit unrestricted re-distribution.
This includes GPL, MIT License, Apache etc. See this link blow.
http://www.zdnet.com/blog/burnette/howto-pick-an-open-source-license-part-1/130

If you want to get a decent over view of Open source licensing see here:
http://www.smashingmagazine.com/2010/03/24/a-short-guide-to-open-source-and-similar-licenses/ or

this http://openacs.org/about/licensing/open-source-licensing

Hence, redistribution is essential element of Open source license, hence, i guess these existing licenses formats are not for you.

It is a legitimate question who do you sell software with code but without re-distribution rights. This actually falls under forming a commercial license. This is often otherwise called EULA. This is not as hard though.

Few things might be as follows:
a. Ensure the copyright in each file of code.
b. Define terms of warranty as applicable.
c. Terms of usage - for example number of installations, or users, or any such unit etc. that translates to amount of money paid.
d. Negate the terms of re-distribution.
e. Condition for payments for any modification.
f. Declaration of patents and intellectual property.

It's is not hard to craft such a license for yourself. Of course, it is very hard to find if someone is actually violating and distributing the code without permission.


问:
Did the developers of Java consciously abandon RAII?
As a long-time C# programmer, I have recently come to learn more about the advantages of Resource Acquisition Is Initialization (RAII).  In particular, I have discovered that the C# idiom:

```<code>using (var dbConn = new DbConnection(connStr)) {
    // do stuff with dbConn
}
</code>```

has the C++ equivalent:

```<code>{
    DbConnection dbConn(connStr);
    // do stuff with dbConn
}
</code>```

meaning that remembering to enclose the use of resources like DbConnection in a using block is unnecessary in C++ !  This seems to a major advantage of C++.  This is even more convincing when you consider a class that has an instance member of type DbConnection, for example

```<code>class Foo {
    DbConnection dbConn;

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

In C# I would need to have Foo implement IDisposable as such:

```<code>class Foo : IDisposable {
    DbConnection dbConn;

    public void Dispose()
    {
        dbConn.Dispose();
    }
}
</code>```

and what's worse, every user of Foo would need to remember to enclose Foo in a using block, like:

```<code>   using (var foo = new Foo()) {
       // do stuff with "foo"
   }
</code>```

Now looking at C# and its Java roots I am wondering... did the developers of Java fully appreciate what they were giving up when they abandoned the stack in favor of the heap, thus abandoning RAII?

(Similarly, did Stroustrup fully appreciate the significance of RAII?)

答:
You already called out the rough equivalent to this in C# with the Dispose method.  Java also has finalize.  NOTE: I realize that Java's finalize is non-deterministic and different from Dispose, I am just pointing out that they both have a method of cleaning resources alongside the GC.

If anything C++ becomes more of a pain though because an object has to be physically destroyed.  In higher level languages like C# and Java we depend on a garbage collector to clean it up when there are no longer references to it.  There is no such guarantee that DBConnection object in C++ doesn't have rogue references or pointers to it.

Yes the C++ code can be more intuitive to read but can be a nightmare to debug because the boundaries and limitations that languages like Java put in place rule out some of the more aggravating and difficult bugs as well as protect other developers from common rookie mistakes.

Perhaps it comes down to preferences, some like the low-level power, control and purity of C++ where others like myself prefer a more sandboxed language that are much more explicit.


问:
VB.Net vs C# debate
I've been in workplaces where, at the start of a project, the "Should we use VB.Net or C#" question has been raised.

Granted, it's probably less common to have to make that decision now than it was in the early days of .Net, particularly given the trend towards language convergence, but it can still be a heated debate.

So, between VB.Net and C#, Which language do you prefer and why?

答:
Well, today there's little to none real reason to use VB.net. In the beginning it was just a way to give give VB programmers a familiar syntax, but was essentially a BASIC-like remapping of C#. So its only real advantage is a more familiar syntax, and its BASIC syntax is also its real only limit.

Over the time the two languages evolved alongside, the only significant difference is the my  pseudo namespace.

I would advice every .net programmer that is not familiar to C# to learn it, as the community is fairly larger and the C-like syntax is common to most of the more used languages.

Title: VB.Net vs C# debate


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
Programming is one of the most
  difficult branches of applied
  mathematics; the poorer mathematicians
  had better remain pure mathematicians

— Edsger W. Dijkstra


答:
Great! I see you found out about Code Contracts for .NET. Code Contracts goes a lot further than your average assertions, of which the static checker is the best example. This might not be available to you if you haven't got Visual Studio Premium or higher installed, but it is important to understand the intention behind it if you are going to use Code Contracts.

When you apply a contract to a function, it literally is a contract. That function guarantees to behave according to the contract, and is guaranteed to only be used as defined by the contract.

In your given example, the DoSomethingElse() function doesn't live up to the contract as specified by DoSomething(), as null can be passed, and the static checker will indicate this problem. The way to resolve this is by adding the same contract to DoSomethingElse().

Now, this means there will be duplication, but this duplication is necessary as you choose to expose the functionality across two functions. These functions, although private, can be called from different places in your class as well, so the only way to guarantee that from any given call the argument will never be null is to duplicate the contracts.

This should make you reconsider why you split the behavior in two functions in the first place. It has always been my opinion (contrary to popular belief) that you shouldn't split functions which are only called from one place. By exposing the encapsulation by applying the contracts this becomes even more evident. It seems I found an extra argumentation for my cause! Thank you! :)

Title: code contracts/asserts: what with duplicate checks?

Body:
I'm a huge fan of writing asserts, contracts or whatever type of checks available in the language I'm using. One thing that bothers me a bit is that I'm not sure what the common practice is for dealing with duplicate checks.

Example situation: I first write the following function

```<code>void DoSomething( object obj )
{
  Contract.Requires<ArgumentNullException>( obj != null );
  //code using obj
}
</code>```

then a few hours later I write another function that calls the first one. As everything is still fresh in memory, I decide not to duplicate the contract, since I know that DoSomething wil check for a null object already:

```<code>void DoSomethingElse( object obj )
{
  //no Requires here: DoSomething will do that already
  DoSomething( obj );
  //code using obj
}
</code>```

The obvious problem: DoSomethingElse now depends on DoSomething for verifying that obj is not null. So should DoSomething ever decide not to check anymore, or if I decide to use another function obj might not be checked anymore. Which leads me to writing this implementation after all:

```<code>void DoSomethingElse( object obj )
{
  Contract.Requires<ArgumentNullException>( obj != null );
  DoSomething( obj );
  //code using obj
}
</code>```

Always safe, no worries, except that if the situation grows the same object might be checked a number of times and it's a form of duplication and we all know that's not so good.

What is the most common practice for situation like these?


问:
(Dis-)advantages of structural typing
I’ve just watched this talk by Daniel Spiewak where he talks about the advantages of structural typing as compared to Scala’s ans Java’s nominal typing. One example for this difference would be the following Java code

```<code>public interface Foo {
  public int length();
}
public interface Bar {
  public int length();
}

Foo f = ...;
Bar b = f;
</code>```

which of course would not compile because type compatibility between Foo and Bar is determined by name.

A structural type system on the other hand could declare both types being equal or compatible and thus, amongst other things, allow for checked duck typing.

Now I think I do understand most of the advantages of a structural type system but I wonder if it would not invalidate type safety from examples like the following

```<code>class Foo {
  class Bar { /* ... */ }
  def takeBar(b: Bar) = { /* ... */ }
  def getBar: Bar = new Bar
}

val foo1 = new Foo
val foo2 = new Foo
foo1.takeBar(foo1.getBar) // should compile
foo1.takeBar(foo2.getBar) // should not compile
</code>```

Is my understanding correct that in a structural type system the last line would compile as well and if so, wouldn’t this be a disadvantage with respect to type safety?

答:
Actually, path-dependent types are orthogonal to structural vs nominal typing.  It's not really clear what an inner class means in the context of a simple structurally-typed language.  It is, however, very possible to define this.  If you were to define inner classes in a structurally typed context, you would need to ensure that cases like the one you listed would be rejected (for precisely the same reasons that Scala rejects them).

You would reject such cases by doing the same thing that Scala does: model the path-dependent type as an existential type.  The same pack/unpack procedure surrounding object access would hold, and the results would look almost identical to what Scala does.  The results may seem like a nominal type equality, but it would still be a structural type system since the question of type compatibility will still be decided on interface rather than name.

Structural typing does have a lot of implications, but (perhaps surprisingly) most of the same concepts we all know and love from nominal type systems do carry over into structural.  Structural typing is nothing more than a different way of defining type compatibility.

OwnerDisplayName: Debilski

Title: (Dis-)advantages of structural typing


问:
Common practice for abandonware in SVN
I have a general repository for small utilities (which were deemed too small at the time to warrant their own repository. 'Nother problem of itself maybe), some of which are deprecated and likely to never serve again. But one rule where I work is to never throw anything away. Deleting from SVN means it's not really deleted, it's just in the history somewhere, but that can still be hazardous in case you need to find that old thing again.

What would be the best strategy for keeping deprecated items, but also keeping them out of the way?

答:
What would be the best strategy for keeping deprecated items, but also
  keeping them out of the way?

Move all your deprecated projects into a 'deprecated' directory.

Edit: I wrote previously that you could get svn to ignore files in the deprecated directory, but that turns out not to be the case. If you're used to updating all your projects at once but would like to avoid checking out deprecated projects, consider keeping all your active projects in one directory and deprecated projects in another.

Title: Common practice for abandonware in SVN


问:
A simple ways to improve the release quality in RAD environment
A bit of a background here - we are a small team (of 5) of RAD developers responsible for internal software development in a big non-software company. "Internal software" varies from a desktop .NET application using MSSQL server as a backend to Python scripts running on the background  to MS Word documents and templates - a zoo of technologies.

The whole team consist of all-arounders able to get the requirements from users, code it up, test it and deploy into production. Once the software in the production it is being looked after by another team but it usually easy for us to intervene if something goes wrong.

All sounds good so far, but there is a problem - being a RAD team we have to release often, and there is no day going by without us releasing new versions of one or two applications(or it could be a script, updated word document, C++ console app, etc) into the production. We do a development testing and also do involve end-users by letting them run the software in UAT environment ...

... but the bugs are creeping in to production anyway. Users do understand that these bugs and the occasional instability is the price they are paying for getting what they want really quickly, but at the same time it got us thinking - perhaps we could improve our development or a release practices to improve the stability of the software and reduce the number of bugs we introduce when adding a new functionality.

The good thing - we don't really have much of the processes in the first place, so it should be easy to start improving, the bad thing - being a small RAD team we don't really have the much time and resources to implement something big, but we have been thinking about the following initiatives and would welcome any feedback, tips, hints and suggestions.

Currently some of the applications are being released into the production straight after the developer testing, bypassing the user acceptance testing. That practice should be discontinued and even a small change has to be tested by a end-user. Each application will have a dedicated beta-tester selected from the end-users. Only after a beta-tester has ok-ed the new release it is promoted from test to production environment.

We don't conduct code reviews - but we'll start doing code reviews before one of us checkin the changeset. I was also thinking about a "rollout review" - basically one of the developers has to sit next with the other watch him/her doing the software rollout (copy binaries, update configs, add new table to database, etc) - it usually only takes a 5-10 minutes so it won't take much of a "rollout review" time.

How to miminise the rollback time when a new release is proven to be buggy enough to be pullout from production and to be replaced by a good previous version. We do store a history of all releases (as a binaries) to make it easy to go one version back - and though it is quick "overwrite a newly released binaries with a previous versions binaries" it is still a manual process which is error prone and demanding at times "what if the rollback will fail and will render the system unusable instead of buggy".

This is where we ran out of our ideas and we'd like to get your feedback on these and if you could share some simple release / dev process improvement advices - that would be awesome.

答:
Whenever I hear about defects, my first questions are about where the defects originate and where they get detected and removed. Defect Removal Efficiency is a good way of measuring and tracking this. By knowing where defects originate and working to improve the processes at those phases, you can reduce time and cost of a project. It's well known that it's cheaper to fix defects closer to their point of injection, so once you know where the defects are coming from, you can then look at activities changes to improve those phases.

Once you have information about where the defects are coming from, you can look at exactly what techniques and technologies you want to apply. Reviews of requirements, design, and code, automated tests, static analysis, continuous integration, and more extensive user-driven testing might be options that you should look at, depending on what phases generate defects.

To expand on your desire for code reviews, you should also consider different levels of code reviews based on the priority and risk of a module. Low risk, low priority modules might not need a code review at all, or perhaps just a simple desk check, where another developer just reads the code on his/her own and provides comments, would work. Other code review techniques include pair programming, walkthroughs, critiques, and inspections with various numbers of developers.

For the purposes of rolling back, I would look to automate that process using some kind of scripts to make it faster and less error prone. In a perfect world, I would want to increase the quality of shipped products such that it isn't necessary to roll back, and you can achieve this. Having the capability, though, might be a good idea, but make it as painless as possible.


答:
Now looking at C# and its Java roots I am wondering... did the developers of Java fully appreciate what they were giving up when they abandoned the stack in favor of the heap, thus abandoning RAII?

(Similarly, did Stroustrup fully appreciate the significance of RAII?)

I am pretty sure Gosling did not get the significance of RAII at the time he designed Java. In his interviews he often talked about reasons for leaving out generics and operator overloading, but never mentioned deterministic destructors and RAII.

Funny enough, even Stroustrup wasn't aware of the importance of deterministic destructors at the time he designed them. I can't find the quote, but if you are really into it, you can find it among his interviews here: http://www.stroustrup.com/interviews.html

Title: Did the developers of Java consciously abandon RAII?

Body:
As a long-time C# programmer, I have recently come to learn more about the advantages of Resource Acquisition Is Initialization (RAII).  In particular, I have discovered that the C# idiom:

```<code>using (var dbConn = new DbConnection(connStr)) {
    // do stuff with dbConn
}
</code>```

has the C++ equivalent:

```<code>{
    DbConnection dbConn(connStr);
    // do stuff with dbConn
}
</code>```

meaning that remembering to enclose the use of resources like DbConnection in a using block is unnecessary in C++ !  This seems to a major advantage of C++.  This is even more convincing when you consider a class that has an instance member of type DbConnection, for example

```<code>class Foo {
    DbConnection dbConn;

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

In C# I would need to have Foo implement IDisposable as such:

```<code>class Foo : IDisposable {
    DbConnection dbConn;

    public void Dispose()
    {
        dbConn.Dispose();
    }
}
</code>```

and what's worse, every user of Foo would need to remember to enclose Foo in a using block, like:

```<code>   using (var foo = new Foo()) {
       // do stuff with "foo"
   }
</code>```

Now looking at C# and its Java roots I am wondering... did the developers of Java fully appreciate what they were giving up when they abandoned the stack in favor of the heap, thus abandoning RAII?

(Similarly, did Stroustrup fully appreciate the significance of RAII?)


答:
Your description of the holes of using is incomplete. Consider the following problem:

```<code>interface Bar {
    ...
}
class Foo : Bar, IDisposable {
    ...
}

Bar b = new Foo();

// Where's the Dispose?
</code>```

In my opinion, not having both RAII and GC was a bad idea. When it comes to closing files in Java, it's malloc() and free() over there.

Body:
Your description of the holes of using is incomplete. Consider the following problem:

interface Bar {
    ...
}
class Foo : Bar, IDisposable {
    ...
}

Bar b = new Foo();

// Where's the Dispose?

In my opinion, not having both RAII and GC was a bad idea. When it comes to closing files in Java, it's malloc() and free() over there.


答:
Java7 introduced something similar to the C# using:  The try-with-resources Statement

a try statement that declares one or more resources. A resource is as an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource...

So I guess they either didn't consciously choose not to implement RAII or they changed their mind meanwhile.


问:
OO best practices for C programs
"If you really want OO sugar - go use C++" -- was the immediate response I got from one of my friends when I asked this. I know two things are dead wrong here. First OO is NOT 'sugar', and second, C++ has NOT absorbed C.

We need to write a server in C (the front-end to which will be in Python), and so I am exploring better ways to manage large C programs.

Modeling a large system in terms of objects, and object interactions makes it more manageable, maintainable and extensible. But when you try to translate this model into C which does not bear objects (and everything else thereof), you're challenged with some important decisions.

Do you create a custom library to provide the OO abstractions your system needs? Things like objects, encapsulation, inheritance, polymorphism, exceptions, pub/sub (events/signals), namespaces, introspection, etc. (for example GObject or COS).

Or, you just use the basic C constructs (struct and functions) to approximate all your object classes (and other abstractions) in ad-hoc ways. (for example, some of the answers to this question on SO)

The first approach gives you a structured way to implement your entire model in C. But it also adds a layer of complexity that you have to maintain. (Remember, complexity was what we wanted to reduce by using objects in the first place).

I don't know about the second approach, and how effective it is at approximating all the abstractions you might require.

So, my simple questions is: What are the best practices in realizing an object oriented design in C. Remember I am not asking HOW to do it. This and this questions talk about it, and there's even a book on this. What I am more interested in are some realistic advice/examples that address the real issues that show up when dong this.

Note: please don't advice why C shouldn't be used in favor of C++. We've gone well past that stage.

答:
Object-orientation boils down to three things:

1) Modular program design with autonomous classes.

2) Protection of data with private encapsulation.

3) Inheritance/polymorphism and various other helpful syntax like constructors/destructors, templates etc.

1 is most important by far, and it is also completely language-independent, it is all about program design. In C you do this by creating autonomous "code modules" consisting of one .h file and one .c file. Regard this as the equivalent of an OO class. You can decide what should be placed inside this module through common sense, UML or whatever method of OO design you are using for C++ programs.

2 is also quite important, not only to protect againt intentional access to private data, but also to protect against unintentional access, ie "namespace clutter". C++ does this in more elegant ways than C, but it can still be achieved in C by using the static keyword. All variables you would have declared as private in a C++ class, should be declared as static in C and placed at file scope. They are only accessible from within their own code module (class). You can write "setters/getters" just as you would in C++.

3 is helpful but not necessary. You can write OO programs without inheritance or without constructors/destructors. These things are nice to have, they can certainly make the programs more elegant and perhaps also safer (or the opposite if used carelessly). But they are not necessary. Since C supports neither of these helpful features, you'll simply have to do without them. Constructors can be replaced with init/destruct functions.

Inheritance can be done through various struct tricks, but I would advice against it, since it will likely just make your program more complex without any gain (inheritance in general should be carefully applied, not only in C but in any language).

Finally, every OO trick can be done in C. Axel-Tobias Schreiner's book "Object-oriented programming with ANSI C" from the early 90s proves this. However, I would not recommend that book to anyone: it adds an unpleasant, strange complexity to your C programs that is just not worth the fuss. (The book is available for free here for those still interested despite my warning.)

So my advise is to implement 1) and 2) above and skip the rest. It is a way of writing C programs that has proven successful for well over 20 years.

Title: OO best practices for C programs


答:
I work in a small dev team also (only 2 of us) and we experienced similar issues you have mentioned.  The main issue for us is that we both tend to work on separate tasks and it was becoming too common for us to complete a task/feature, test it (tested by developer only) and release quickly.  This was resulting in a lot of small releases with users reporting small bugs that should have easily been picked up in testing.

In order to improve our process I started by introducing a Kanban board.  The board was very simple to start with and only had a few columns (setup using a whiteboard, index cards and coloured magnets):

Backlog | To Do | Done

However, this quickly evolved to mirror our actual process:

Backlog | Development | Dev. Test | UAT | Done | Released

Along with the board we have a rule that each Task/Feature must be tested by another developer (as well as by the developer that implemented the feature).  So by the time the a card reaches the 'Done' column it should have been tested by at least 2 developers and also User Acceptance Tested.

There are a lot of other benefits to using Kanban.  For us it has improved communication and helped us to share knowledge as we are both involved to some degree in each task.  It has also improved our release process as we can now see exactly what tasks/features are ready to release/done and can sometimes hold off on releasing if we know other taks will be done soon.  For people outside the team, the board also acts as a quick reference to see what tasks we have scheduled, current work in progress and what was recently released.

Just as an aside, we use coloured magnets (one per developer) to flag the card we are curently working on but another option is to add swim lanes (rows), one per developer and place Kanban cards in relevant swim lanes.  Again this helps as a quick reference to see what each developer is currently working on.

Other links I found useful:

Kanban Applied to Software Development: from Agile to Lean

A Kanban System for Software Engineering - Video

Hopefully Kanban would address point 1. in your question.  In relation to code reviews, we do this at the dev testing stage so that any changes required after review are dev tested again before going to UAT.  Rolling back depends on your environment but we deploy application files to Terminal Servers using batch files which rename current files and copy across new files from a central server and we can roll back fairly easily by placing the back up (previous files) in the central location and re-running scripts.

Title: A simple ways to improve the release quality in RAD environment

Body:
A bit of a background here - we are a small team (of 5) of RAD developers responsible for internal software development in a big non-software company. "Internal software" varies from a desktop .NET application using MSSQL server as a backend to Python scripts running on the background  to MS Word documents and templates - a zoo of technologies.

The whole team consist of all-arounders able to get the requirements from users, code it up, test it and deploy into production. Once the software in the production it is being looked after by another team but it usually easy for us to intervene if something goes wrong.

All sounds good so far, but there is a problem - being a RAD team we have to release often, and there is no day going by without us releasing new versions of one or two applications(or it could be a script, updated word document, C++ console app, etc) into the production. We do a development testing and also do involve end-users by letting them run the software in UAT environment ...

... but the bugs are creeping in to production anyway. Users do understand that these bugs and the occasional instability is the price they are paying for getting what they want really quickly, but at the same time it got us thinking - perhaps we could improve our development or a release practices to improve the stability of the software and reduce the number of bugs we introduce when adding a new functionality.

The good thing - we don't really have much of the processes in the first place, so it should be easy to start improving, the bad thing - being a small RAD team we don't really have the much time and resources to implement something big, but we have been thinking about the following initiatives and would welcome any feedback, tips, hints and suggestions.

Currently some of the applications are being released into the production straight after the developer testing, bypassing the user acceptance testing. That practice should be discontinued and even a small change has to be tested by a end-user. Each application will have a dedicated beta-tester selected from the end-users. Only after a beta-tester has ok-ed the new release it is promoted from test to production environment.

We don't conduct code reviews - but we'll start doing code reviews before one of us checkin the changeset. I was also thinking about a "rollout review" - basically one of the developers has to sit next with the other watch him/her doing the software rollout (copy binaries, update configs, add new table to database, etc) - it usually only takes a 5-10 minutes so it won't take much of a "rollout review" time.

How to miminise the rollback time when a new release is proven to be buggy enough to be pullout from production and to be replaced by a good previous version. We do store a history of all releases (as a binaries) to make it easy to go one version back - and though it is quick "overwrite a newly released binaries with a previous versions binaries" it is still a manual process which is error prone and demanding at times "what if the rollback will fail and will render the system unusable instead of buggy".

This is where we ran out of our ideas and we'd like to get your feedback on these and if you could share some simple release / dev process improvement advices - that would be awesome.


答:
In C++, you use more general-purpose, lower-level language features (destructors automatically called on stack-based objects) to implement a higher-level one (RAII), and this approach is something the C# / Java folks seem not to be too fond of. They'd rather design specific high-level tools for specific needs, and provide them to the programmers ready-made, built into the language. The problem with such specific tools is that they are often impossible to customize (in part that's what makes them so easy to learn). When building from smaller blocks, a better solution may come around with time, while if you only have high-level, built-in constructs, this is less likely.

So yeah, I think (I wasn't actually there...) it was a concious decision, with the goal of making the languages easier to pick up, but in my opinion, it was a bad decision. Then again, I generally prefer the C++ give-the-programmers-a-chance-to-roll-their-own philosophy, so I'm a bit biased.


问:
How to improve your ability to debug existing code
A common task in the working world is dealing with existing, but buggy code. What are some tips to improve your skills as a debugger?</p>

答:
Two things, based on spending most of the last 22 years maintaining code other people wrote.

Understand the kinds of bugs you tend to write.

For instance, I'm a very meticulous coder, so once my code compiles, it's usually free of trivial bugs. So my bugs tend to be weird complicated things like thread deadlocks. On the flip side, I have friend who mostly writes trivial bugs - semicolons at the end of C++ for loops, so the next line only gets executed once, that kind of thing.

Don't assume other people write the same kinds of bugs you do.

I don't know how many times I've wasted time pulling out the big debugging guns, assuming a bug was my kind of really subtle weird thing, only to have my friend look over my shoulder and go, "Did you notice that extra semicolon?" After years of that, I first go for the trivial, low-hanging fruit when looking at other peoples' code.