答:
If the author of the library is unable to reproduce the bug based upon your report, then it is unreasonable to expect him to spend a lot of time on it, let alone fix it.

But you also have a limited amount of time spend working on a product that is peripheral to your interest.  Unfortunately, this may mean that the bug continues to exist, and no work is done on resolving it.

Fortunately this is not necessarily a disaster -- while in an ideal world, all software would be bug free, that isn't the case, and so we have to prioritize based upon the problems it causes US.

This means that it is indeed your responsibility to develop a reproducible test case IF YOU WANT IT FIXED.  You may not care whether it gets fixed, and in that case, you have done everything that can and should be expected of you.  You may want it fixed, but not enough to devote time to make it reproducible at this time.  That is perfectly acceptable.

Reporting a bug to the best of your ability in the time you have to deal with it is simply good citizenship, you don't need to go beyond that unless it is necessary for your program.  And you may not want to do so even then, there may be another library that you could use, or it may be possible to roll your own in a reasonable period of time.  Basically it's up to you to decide what and what kind of effort it is worth to you.

Title: Responsibility to reproduce bugs


问:
I believe I have mixed C and C++ code when I shouldn't have; Is this a problem and how to rectify?
Background/Scenario

I started writing a CLI application purely in C (my first proper C or C++ program that wasn't "Hello World" or a variation thereof). Around midway through I was working with "strings" of user input (char arrays) and I discovered the C++ string streamer object. I saw that I could save code using these, so I used them through the application. This means that I have changed the file extension to .cpp and now compile the app with g++ instead of gcc. So based on this, I would say the application is now technically a C++ application (although 90%+ of the code is written in what I would call C, as there is lots of cross-over between the two language given my limited experience of the two). It is a single .cpp file around 900 lines long.

Important Factors

I want the program to be free (as in money) and freely distributable and usable for all to have. My concern is that someone will look at the code and think something to the effect of:

Oh look at the coding, it's awful, this program can't help me

When potentially it could! Another matter is the code being efficient (it is a program for testing Ethernet connectivity). There should be no parts of the code that are so inefficient that they can severely hinder the performance of the application or its output. However, I think that is a question for Stack Overflow when asking for help with specific functions, methods, object calls, etc.

My question

Having (in my opinion) mixed C and C++ where perhaps I shouldn't. Should I look to rewrite it all in C++ (by this, I mean implement more C++ objects and methods where perhaps I have coded something in a C style that can be condensed using newer C++ techniques), or remove the use of string streamer objects and bring it all "back" to C code? Is there a correct approach here? I am lost and need some guidance on how to keep this application "Good" in the eyes of the masses, so they will use it and benefit from it.

The Code - Update

Here is a link to the code. It is circa 40% comments, I comment nearly every line until I feel more fluent. In the copy I have linked to though, I have removed pretty much all the comments. I hope this doesn't make it too hard to read. I am hoping though that no one should need to fully understand it. If I have made fatal design flaws though, I am hoping they should be identifiable easily. I should also mention, I am writing a couple of Ubuntu desktops and laptops. I'm not intending to port the code to other operating systems.

答:
It is bad form to mix C and C++. They are distinct languages and really should be treated as such. Pick whichever one you are most comfortable with and try to write idiomatic code in that language.

If C++ is saving you a lot of code, then stick with C++ and re-write the C parts. I doubt a performance difference will even be noticeable, if that's what you're concerned about.

ContentLicense: CC BY-SA 3.0


答:
C++ is a very complex language, in the sense that it has a lot of features. It is also a language that supports multiple paradigms, meaning that it allows you to write entirely procedural code without using any objects.

So because C++ is so complex, you often see people use some limited subset of its features in their code. Beginners often just use the stream I/O, the string objects, and new/delete instead of malloc/free, and maybe references instead of pointers.  As you learn about the object-oriented features, you may start writing in a style called "C with classes". Eventually, as you learn more about C++, you start using templates, RAII, STL, smart pointers, etc.

The point I am trying to make is that learning C++ is a process that takes time. Yes, right now your code probably looks like it was written by a C programmer trying to write C++. And since you are just learning, that's perfectly ok. However, it does make me cringe, when I see this kind of thing in production code written by seasoned programmers who should know better.

Just remember, a good Fortran programmer can write good Fortran code in any language. :)

Title: I believe I have mixed C and C++ code when I shouldn't have; Is this a problem and how to rectify?

Body:
Background/Scenario

I started writing a CLI application purely in C (my first proper C or C++ program that wasn't "Hello World" or a variation thereof). Around midway through I was working with "strings" of user input (char arrays) and I discovered the C++ string streamer object. I saw that I could save code using these, so I used them through the application. This means that I have changed the file extension to .cpp and now compile the app with g++ instead of gcc. So based on this, I would say the application is now technically a C++ application (although 90%+ of the code is written in what I would call C, as there is lots of cross-over between the two language given my limited experience of the two). It is a single .cpp file around 900 lines long.

Important Factors

I want the program to be free (as in money) and freely distributable and usable for all to have. My concern is that someone will look at the code and think something to the effect of:

Oh look at the coding, it's awful, this program can't help me

When potentially it could! Another matter is the code being efficient (it is a program for testing Ethernet connectivity). There should be no parts of the code that are so inefficient that they can severely hinder the performance of the application or its output. However, I think that is a question for Stack Overflow when asking for help with specific functions, methods, object calls, etc.

My question

Having (in my opinion) mixed C and C++ where perhaps I shouldn't. Should I look to rewrite it all in C++ (by this, I mean implement more C++ objects and methods where perhaps I have coded something in a C style that can be condensed using newer C++ techniques), or remove the use of string streamer objects and bring it all "back" to C code? Is there a correct approach here? I am lost and need some guidance on how to keep this application "Good" in the eyes of the masses, so they will use it and benefit from it.

The Code - Update

Here is a link to the code. It is circa 40% comments, I comment nearly every line until I feel more fluent. In the copy I have linked to though, I have removed pretty much all the comments. I hope this doesn't make it too hard to read. I am hoping though that no one should need to fully understand it. If I have made fatal design flaws though, I am hoping they should be identifiable easily. I should also mention, I am writing a couple of Ubuntu desktops and laptops. I'm not intending to port the code to other operating systems.


答:
It sounds you are recapitulating exactly the path a lot of old C programmers took when going to C++.  You're using it as a "better C".  Twenty years ago this made some sense, but at this point there are so many more powerful constructs in C++ (like the Standard Template Library) that it rarely makes sense now.  At a minimum, you likely should do the following to avoid giving C++ programmers aneurysms when looking at your code:

Use streams instead of the ?printf family.

Use new instead of malloc.

Use the STL container classes for all data structures.

Use std::string instead of char* wherever possible

Understand and use RAII

If your program is short (and ~900 lines seems short) I personally don't think trying to create a robust set of classes is required or even useful.


问:
Responsibility to reproduce bugs
I'm developing a program using a library made by another programmer (he works in the same company). Recently I discovered a leak in the library, which happens under certain network conditions  after a few hours of running. I filed a bug with description of conditions to make this leak happen. That developer answered that "this is not enough", "it's not his responsibility to reproduce bugs" and I have to create unit test to reproduce this bug, otherwise he doesn't do anything.

Is he right?

What I can do in this situation? Creating unit test is impossible, because it depends on some random network timings.

答:
You found a bug, you reported it and he's being a jerk about it.

Had the two of you been close friends he would have done something to help, but he'd rather just push the issue back.

You can do more, by reporting more details and trying to support your claims that it's leaking memory. Still, you have your own responsibilities and need to finish your own work.

Log as much information into the bug tracker as you can, and move on.

If you see this person again in the future. Be friendly, try to talk about common interests and understand that good relationships are far more effect way of getting things fixed, then any amount of facts you can provide to support a claim.

Title: Responsibility to reproduce bugs


问:
Scalable spring core with AMQP?
I use 3 standard Spring MVC war, which share a common core (Services, DAO, and Models).
The main problem is when I plan to deploy all the 3 wars on a same server. I have the Core Application Context instantiated 3 times.

I know it's possible to share a common context using an EAR, but for scalability purposes I have to keep all 3 wars, as 3 distinct units, which could deploy in a different count each.

My question is about an architectural choice:

Is it a good idea to split the Service layer used by my Controllers in a facade + commands (pattern) which can be distributed to the core (backend) via an AMQP? So that I could share requests across multiple cores.

答:
Yes; it is a good idea to put your core layer on a different node and to make it communicate with the upper 3 distinct layers via AMQP. This brings horizontal scalability - not only can you put the upper layers and the core layer onto different nodes but you can replicate the core onto 2 or more nodes. Also you can have your message broker distributed onto many nodes (for example RabbitMQ supports clustering). AMQP is probably a better choice over JMS since it is more flexible by allowing you to easily integrate modules written in different language; also Spring has a good support for AMQP via Spring AMQP.

The alternative, as you have mentioned it, would have been to put all in a ear and deploy it to a Java EE server which can be distributed onto many nodes. But since you already have Spring, this requires more effort.

Title: Scalable spring core with AMQP?


问:
Easily add metrics to measure java code usability
I'm trying to create a process for better understand what's happening in my code. I want to create metrics to automatically give my answers about simple or complex questions like:

How many times a url was clicked? (how many requests arrived to a certain servlet method)

How many times a certain user requested the same page?

How many requests are pending in a queue on average?

and so on...

Is there an easy way to do this automatically and elegantly (for example - attribute like @CountHits would be great)?

I found this open source: http://metrics.codahale.com/getting-started/#reporting-via-jmx
But it's too coupled to the code. Not so elegant :/

答: As far as I know there aren't anything like @CountHits. But if you are so keen in knowing the metrics like the no of clicks and all I would suggest you to use a logging library like log4j to log all the event details and then use a search/analyze tool like Splunk(http://www.splunk.com/) to find out whatever interests you in an elegant way.</p>


问:
What makes Common Lisp "big"?
I've been learning both Common Lisp and Racket, and one thing that I consistently hear is that Racket is a much "smaller" language than Common Lisp. I was wondering what this really meant. As far as I can tell, the syntax for Common Lisp isn't that much bigger than for Racket.

Basically, I'm wondering what exactly about common lisp is bigger. Does it have more syntax that I just don't know about? Does it have bigger environments? Bigger executables? Bigger libraries? Or some combination thereof?

Please, this is not a "which one is better" thread, I would just like to know exactly what "bigger" means.

答:
Common Lisp has a large standard library. Then again, so does Racket.

The main difference is that Racket separates everything out into modules, so that programs that don't use all of the standard library don't have to see it. You just import the bits you want to use, and the rest is neatly hidden away.

Title: What makes Common Lisp "big"?


答:
Let's start at the beginning: mixed C and C++ code is fairly common. So you're in a big club to start with. We have huge C codebases in the wild. But for obvious reasons many programmers refuse to write at least new stuff in C, having access to C++ in the same compiler, new modules start to be written that way -- at first just leaving the existing parts alone.

Then eventually some existing files get recompiled as C++, and some bridges can be deleted... But it may take really long time.

You are ahead somewhat, your full system is now C++, just most of it is written "C-style". And you see mix of styles a problem, what you should not: C++ is a multi-paradigm language supporting many styles, and allow them to co-exist for good. Actually that is the main strength, that you are not forced to a single style. One that would be suboptimal here and there, with some luck not everywhere.

Re-working the codebase is a good idea, IF it is broken. Or if it is in the way of development. But if it works (in the original sense of word), please follow the most basic engineering principle: if it ain't broke, don't fix it.   Leave the cold parts alone, put your effort where it counts.   On the parts that are bad, dangerous -- or in new features, and just refactor parts to make them a bed.

If you seek general things to address, here's what worth evicting from a C codebase:

all the str* functions and char[] -- replace them with a string class

if you use sprintf, create a version that returns a string with the result, or puts it in the string, and replace usage. (If you never bothered with streams do yourself a favor and just skip them, unless you like them; gcc provides perfect type safety out of the box for checking formats, just add the proper attribute.

most malloc and free -- NOT to with new and delete, but vector, list, map and other collectons.

the rest of memory management (after the previous two points it must be pretty rare, cover with smart pointers or implement your special collections

replace all other resource usage (FILE*, mutex, lock, etc) to use RAII wrappers or classes

When you're done with that you approach the point where the codebase can be reasonably exception-safe, so you can drop return-code football using exceptions and rare try/catch in high-level functions only.

Beyond that just write new code in some healthy C++, and if some classes are born that are good replacement in existing code, pick them up.

I didn't mentions syntax-related stuff, obviously use refs instead of pointers in all new code, but replacing old C parts just for that change is no good value. Casts you must address, eliminate all you can, and use C++ variants in wrapper functions for the remainder.   And very importantly, add const wherever applicable. These interleave with the earlier bullets. And consolidate your macros, and replace what you can make into enum, inline function or template.

I suggest reading Sutter/Alexandrescu's C++ Coding Standards if not yet done and follow them closely.


问:
Dividing monopoly streets in groups
I'm new to object-oriented programming, to java, and to programming in general, and as my first real project I'm trying to program the board game Monopoly.

What I've got so far is an array that can store objects of the class Square (which has various subclasses, like properties, the railroads, chance cards etc.). Player objects take turns in moving around on the board, calling a landedOn() method for whatever square they land on. Properties can be marked with an owner, and thus this owner will receive money if someone lands on his property.

Everything is going good so far, but there is one little thing that bugs me. I'm unsure about how to elegantly divide the houses in groups, or colors. There are a couple of groups of streets on the board, and you can only buy houses if you own all properties in the group. I can imagine how to program this, but the solution seems a bit dirty and "non-general" to me. How do I make a nice general solution?

To clear up: I want to be able to check whether all properties of one type are owned by the same player, in a general way, so that if the groups are changed, a property is added, or changes group, etc., I would not have to change a lot of code.

答:
The most elegant answer is probably an Enum.

Create an enum value for each color group, and when you create your Property object (which inherits from Square), pass the color group as a constructor parameter (since it is a required value to have a valid Property).  Railroad, Utility and the like will not take this parameter, since they don't have groups, and they also inherit directly from Square (not Property).*

To check whether a player has all the properties in a given group, you could use a Lambda expression if you're using Java 8, or simply have a foreach loop along the lines of

```<code>for (property: allProperties)
{
   if (property.getGroup() == targetGroup && property.getOwner() != targetOwner) return false;
}
return true;
</code>```

* It would also be valid to have a GroupedSquare class between Property and Square, with Railroad and Utility also inheriting from it and passing a hard-coded enum value, but I think that's less elegant.

Title: Dividing monopoly streets in groups

Body:
The most elegant answer is probably an Enum.

Create an enum value for each color group, and when you create your Property object (which inherits from Square), pass the color group as a constructor parameter (since it is a required value to have a valid Property).  Railroad, Utility and the like will not take this parameter, since they don't have groups, and they also inherit directly from Square (not Property).*

To check whether a player has all the properties in a given group, you could use a Lambda expression if you're using Java 8, or simply have a foreach loop along the lines of

for (property: allProperties)
{
   if (property.getGroup() == targetGroup && property.getOwner() != targetOwner) return false;
}
return true;

* It would also be valid to have a GroupedSquare class between Property and Square, with Railroad and Utility also inheriting from it and passing a hard-coded enum value, but I think that's less elegant.


答:
In short: you're not going to hell, nothing bad will happen, but you're not going to win any beauty competitions either.

While it is perfectly possible to use C++ as a "better C", you're throwing away many of C++'s benefits, but because you're not restricting yourself to vanilla C, you're not getting any of C's benefits (simplicity, portability, transparency, interoperability) either. In other words: C++ sacrifices some of C's qualities to gain others - for example, C's transparency where you can always see clearly where and when memory allocations happen is traded for C++'s more powerful abstractions.

Since your code seems to work OK now, it's probably not a good idea to rewrite it just for the sake of it: keep it as it is for now, and change it to more idiomatic C++ as you go, one piece at a time, whenever you work on any given part. And keep the lessons thus learned in mind for your next project, most of all this one: C and C++ are not the same language, and you're better off making a choice up-front than deciding to switch to C++ halfway through your project.


问:
How do I (php developer) work with an asp.net developer?
I'm a php developer working on a startup, and my friend,
my partner(a developer also), who is building the startup with me,
is an asp.net/C# developer.

How do we work together collaboratively, as we program in two distinct languages? I know you can use Mono http://mono-project.com to design android applications, (which is java based) by writing C# codes and iOS.

Is there any platform or framework we can use to create php apps by writing codes in C# or a framework that can convert C# codes to php, just like Mono?

答: You should learn ASP.NET/C#. The fact that you say you're a "PHP developer" hints that it's your only language; learning C# will be both a great learning experience and a good career move.  If possible, pair with your friend using one monitor and two keyboards.  Take turns typing code and asking questions. Jon Skeet's book, C# in Depth, is excellent. If it feels too advanced, try Head First C#.


答:
Often, what I've come across in similar situations is an assumption that all bugs should be fixed and while it's admirable, it's definitely a great goal to have (lets face it we never set out to write bugs!) it is ultimately unrealistic in any project of a decent size to fix a bug just because it is a bug (if you can find it!)  That's why we have project management and coding methodologies, patterns & practices etc.

So, one thing I'd say in the library owner's defence (and has been the case when I've worked on some big projects) is that dev time costs money and is a finite resource so the decision as to how a report is handled, who investigates, what tests are produced/needed and ultimately if (and if so, when) a fix is put in place is based purely on business impact.  What is the impact of restarting your long running process once in a while if it fails and can you easily automate that instead (and perhaps shouldn't you be already as a defensive programming measure?) is it just time or is there more to it?

Also look at it from their point of view, a bug report from one user of an unpredictable problem in a bit of code that happens very rarely, only in conjunction with their code, possibly only on one machine and only under a set of unusual timing conditions just won't have a strong justification for a large chunk of dev time to find and fix - if it's even possible.  But if it's a strong enough business case for that user to want/need to take the time to investigate more thoroughly and provide a reliable test case / application or a radically more detailed problem description than their initial one then it could be a whole other ballgame.

This is perhaps an issue of communication that the library owner has not considered putting it that way and if you've got a strong business case (such as your code is costly for the business, has a legal compliance requirement, security hole or has some other major knock-on effect) then it's time to kick it up to management and let them fight it out.

Title: Responsibility to reproduce bugs

Body:
I'm developing a program using a library made by another programmer (he works in the same company). Recently I discovered a leak in the library, which happens under certain network conditions  after a few hours of running. I filed a bug with description of conditions to make this leak happen. That developer answered that "this is not enough", "it's not his responsibility to reproduce bugs" and I have to create unit test to reproduce this bug, otherwise he doesn't do anything.

Is he right?

What I can do in this situation? Creating unit test is impossible, because it depends on some random network timings.


问:
Is a data service API a good idea?
We currently have a monolithic Rails application that is really three separate applications that make use of the same data. In trying to figure out how to properly compartmentalize and break the mono-app into smaller pieces, it seems apparent that we need to have a central data service that the various pieces can communicate with, because I don't want to have to redefine a model layer for each application and/or copy models between the various applications (DRY). The idea is that since the database/persistance (including concepts like validations) are going to be the same for each component, it would make sense to have a service that can be used to query for data and create/update/delete it.

What I'm picturing is essentially a JSON API that sits between the database and my application layer. The API will not immediately be exposed to the "outside world" (although that may be something that occurs in the future); for now, it would just be communicated with internally (ie. to/from a public-facing Rails (or other) app). This API would essentially just abstract persistence logic.

Is this a good idea? Are there any pitfalls that I'm not thinking of?

If this is a good idea, does anyone know of a Rails ORM or a gem that can be used to coordinate this sort of endeavour? My vision is that once a data service is running, the actual Rails application wouldn't be using ActiveRecord anymore, but rather something which would handle querying the data API.

答:
Yes, this is an excellent idea. Using a central set of web services allows you to avoid duplication and feature inconsistencies; it makes the web services the system of record for all your user-facing applications, and they can be covered by a set of homogenous automated tests, rather than trying to cobble together a suite of many types of tests.  I'm not sure what the best approach to creating these web services is, in Ruby; Sinatra can definitely do it. I've personally worked with Pyramid and Django, in the Python ecosystem, and was much happier with Pyramid. Java, of course, has many frameworks for RESTful services; Jersey is the reference implementation of the relevant standard.

For Rails, I'm not sure that there's a good library for adapting ORM objects to RESTful services, unfortunately; it's likely that you will be building custom queries into your web services, to some degree, and that complicates the necessary automation to make the "magic" of an ORM work.  That said, you might be surprised by how much your queries are simplified when you can literally ask for a specific business object representation; many joins and related concepts are irrelevant, and you can likely get by with a simple class that follows links within the body of the response to retrieve other resources that have been exposed to you via hypertext (HATEOAS).

Title: Is a data service API a good idea?


答:
An alternative to an enum by Bobson might be to have the groups as independent objects. By this you don't have to iterate over all atreets to see if a group omplte but can check the individual group only. In Pseudocode the impleemntation might look like this:

```<code>class Group {
    Set<Road> roads;

    bool hasAll(Player player) {
        for (road: roads) {
            if (road.getOwner() != player) {
                return false;
            }
        }
        return true;
  }
}

class Road {
    Player owner;
    Group group;

    bool canBuildHouses(Player player) {
        return group.hasAll(player);
    }
}
</code>```

Over the enum approach this has the benefit that you can mov the group specific logic all in the Group class.

Now OO designes will still not like this due to the cyclic dependency (a Group has to know its member Roads and a Road has to know its Group) which can be solved by an event-based approach this would make this specific issue notably more complex but give way more flexibility for i.e. adding special rules as one could add extra rules like bonusses if a player contains a full side of the board or all roads starting with the same letter or something quite easily.

Title: Dividing monopoly streets in groups

Body:
I'm new to object-oriented programming, to java, and to programming in general, and as my first real project I'm trying to program the board game Monopoly.

What I've got so far is an array that can store objects of the class Square (which has various subclasses, like properties, the railroads, chance cards etc.). Player objects take turns in moving around on the board, calling a landedOn() method for whatever square they land on. Properties can be marked with an owner, and thus this owner will receive money if someone lands on his property.

Everything is going good so far, but there is one little thing that bugs me. I'm unsure about how to elegantly divide the houses in groups, or colors. There are a couple of groups of streets on the board, and you can only buy houses if you own all properties in the group. I can imagine how to program this, but the solution seems a bit dirty and "non-general" to me. How do I make a nice general solution?

To clear up: I want to be able to check whether all properties of one type are owned by the same player, in a general way, so that if the groups are changed, a property is added, or changes group, etc., I would not have to change a lot of code.

Body:
An alternative to an enum by Bobson might be to have the groups as independent objects. By this you don't have to iterate over all atreets to see if a group omplte but can check the individual group only. In Pseudocode the impleemntation might look like this:

class Group {
    Set<Road> roads;

    bool hasAll(Player player) {
        for (road: roads) {
            if (road.getOwner() != player) {
                return false;
            }
        }
        return true;
  }
}

class Road {
    Player owner;
    Group group;

    bool canBuildHouses(Player player) {
        return group.hasAll(player);
    }
}

Over the enum approach this has the benefit that you can mov the group specific logic all in the Group class.

Now OO designes will still not like this due to the cyclic dependency (a Group has to know its member Roads and a Road has to know its Group) which can be solved by an event-based approach this would make this specific issue notably more complex but give way more flexibility for i.e. adding special rules as one could add extra rules like bonusses if a player contains a full side of the board or all roads starting with the same letter or something quite easily.


答:
The short answer is no, there isn't.

You (or he) could produce a web API that the other could use for website / mobile apps  or there are frameworks like Phalanger that you can compile assemblies in PHP to use with with other .Net languages (C#, VB.Net, F# etc).  Note: I've not used Phalanger (so please don't take it as a recommendation) and it doesn't convert between languages.

To work in the same project C# and PHP are worlds apart in many respects (for example C# enforces type safety) and a lot of work goes into keeping code, data and presentation/markup separate.  A best practice that in my experience of PHP (mostly Wordpress plugins) is possible but rarely happens, and more so in the types of code snippets that most people learn PHP from.

Ultimately it would be a lot of effort for little return to keep writing both and at most all you could do is produce assemblies for each other to use which is just going to make life difficult eventually.  The books Syrion recommends in his answer are a great start if you want to expand your horizons, otherwise you'll have to try & tempt a C# dev to PHP.

Title: How do I (php developer) work with an asp.net developer?

Body:
I'm a php developer working on a startup, and my friend,
my partner(a developer also), who is building the startup with me,
is an asp.net/C# developer.

How do we work together collaboratively, as we program in two distinct languages? I know you can use Mono http://mono-project.com to design android applications, (which is java based) by writing C# codes and iOS.

Is there any platform or framework we can use to create php apps by writing codes in C# or a framework that can convert C# codes to php, just like Mono?


答:
Common Lisp has a very large standard library in the package COMMON-LISP.

Scheme's standard library is much smaller; every implementation comes with its own library (often large enough to rival CL's), usually in many modules.

As for syntax, as far as I know, Scheme's syntax is "fixed" while Common Lisp has very powerful tools which can be used to modify its reader. E.g., CLOCC/CLLIB/xml.lisp parses XML using READ!

Title: What makes Common Lisp "big"?

Body:
I've been learning both Common Lisp and Racket, and one thing that I consistently hear is that Racket is a much "smaller" language than Common Lisp. I was wondering what this really meant. As far as I can tell, the syntax for Common Lisp isn't that much bigger than for Racket.

Basically, I'm wondering what exactly about common lisp is bigger. Does it have more syntax that I just don't know about? Does it have bigger environments? Bigger executables? Bigger libraries? Or some combination thereof?

Please, this is not a "which one is better" thread, I would just like to know exactly what "bigger" means.


问:
OOP concept: is it possible to update the class of an instantiated object?
I am trying to write a simple program that should allow a user to save and display sets of heterogeneous, but somehow related data. For clarity sake, I will use a representative example of vehicles. The program flow is like this:

The program creates a Garage object, which is basically a class that can contain a list of vehicles objects

Then the users creates Vehicles objects, these Vehicles each have a property, lets say License Plate Nr. Once created, the Vehicle object get added to a list within the Garage object

--Later on--, the user can specify that a given Vehicle object is in fact a Car object or a Truck object (thus giving access to some specific attributes such as Number of seats for the Car, or Cargo weight for the truck)

At first sight, this might look like an OOP textbook question involving a base class and inheritance, but the problem is more subtle because at the object creation time (and until the user decides to give more info), the computer doesn't know the exact Vehicle type.

Hence my question: how would you proceed to implement this program flow? Is OOP the way to go?

Just to give an initial answer, here is what I've came up until now. There is only one Vehicle class and the various properties/values are handled by the main program (not the class) through a dictionary. However, I'm pretty sure that there must be a more elegant solution (I'm developing using VB.net):

```<code>Public Class Garage
    Public GarageAdress As String
    Private _ListGarageVehicles As New List(Of Vehicles)

    Public Sub AddVehicle(Vehicle As Vehicles)
        _ListGarageVehicles.Add(Vehicle)
    End Sub
End Class

Public Class Vehicles
    Public LicensePlateNumber As String
    Public Enum VehicleTypes
        Generic = 0
        Car = 1
        Truck = 2
    End Enum
    Public VehicleType As VehicleTypes
    Public DictVehicleProperties As New Dictionary(Of String, String)
End Class
</code>```

NOTE that in the example above the public/private modifiers do not necessarily reflect the original code

答:
No, there's no way to change the instantiated type of an object.  A Vehicle is a Vehicle, and will remain such until it goes out of scope.

Your choices here are threefold:

Make the type of Vehicle simply a property on the Vehicle object, and default it to Unknown.

This works best when there's little functional difference between a Car and a Truck.

Functions may return different results depending on the VehicleType, and you'll need to handle the Unknown case, but it's trivial to reassign.

Replace the Vehicle with a new object of Car or Truck

This would require either a IsActuallyACar() method on the Vehicle which returns a Car, or a Car constructor which takes a Vehicle as an argument (which is the much better choice).

Going with this method requires you to manually remove the Vehicle from everywhere that it's stored, and replace it with the newly created object.

Rethink your design so that Vehicle is abstract and you don't create the object until you know what type it is.

This is probably the best option from an OO perspective.

You may need to temporarily store data in a non-Vehicle structure as you gather it, but you don't need to worry about changing the type later.

In your described scenario, I suspect #1 is the best choice.  Simply have logic which says "If the object has its type set to Car, then show this, if it's set to Truck show this."  It's not great OOP design, but it handles the "Vehicle of unknown type" the best.


答:
Maybe an objective (if indirect) measure would be useful here. Consider the sizes of the specifications for the languages.

Racket is basically an implementation of R6RS Scheme. The R6RS specification is 90 pages long, total. Of that, about 25 pages are devoted to the language proper, and about 30 more are devoted to its standard library. Along with that, you get some introductory material, references, glossary, etc. Depending on viewpoint, you could argue for a range from about 50 to 90 pages as the "real" total of the specification proper.

The Common Lisp specification is approximately 1400 pages total. Again, that includes ancillary material. Still, I think almost anybody would have to admit/agree that the spec itself is at least 800 pages.

In other words, even if we take the smallest estimate we could for the CL spec, and compare it to the largest estimate possible for the size of R6RS, we end up with the CL spec being roughly 10 times the size of the Scheme specification.

Title: What makes Common Lisp "big"?


问:
Which approach to follow for developing applications targeting multiple platforms?
For applications targeting multiple platforms, I see mainly two development approaches-

Go for some JAVA-like development platform. Have one code solution and let the intermediate runtime handle different platforms. If something goes wrong in any platform, tweak the code a bit. But keep it same for all.

Make modular code separating core logic and UI. Develop separate UIs for respective platforms which will be calling same core libraries. Build the application separately for each of the target platforms.

So, which one to follow? I know, the answer will start with "It depends". But I want to hear your opinions on these approaches and the factors to be considered to choose any of them.

答:
Leverage The Web!

Seriously, if you want THE most bang for your buck, write a web application.

Why?

Web clients don't require much PC power typically.

Web clients are EVERYWHERE.  Not just PC/MAC/Linux, but on phones, mobile devices, and more.

Nothing extra to download for users! (Typically, unless you want something fancy and use Flash, or Silverlight)

All common components are on the server side, and can be Java, .NET, PHP, or a hodgepodge of a bunch of existing components you have.  The client shouldn't care!

Even the two approaches you mentioned are very similar.  The web browser renders HTML for multiple underlying architectures.  Similarly, the JVM interprets Java code in a way that makes sense for the underlying hardware.  The web, however, simply has a broader client base!

ContentLicense: CC BY-SA 2.5


问:
How to handle flag in multiple if-else's
I seem to see this often enough in my code and others. There's nothing about it that seems horribly wrong, but it annoys me as it looks like it can be done better. I suppose a case statement, might make a little more sense, but often variable is a type that does not work well or at all with case statements (depending on language)

```<code>If variable == A
    if (Flag == true)
        doFooA()
    else
        doFooA2

else if variable == B
    if (Flag == true)
        doFooB()
    else
        doFooB2
else if variable == C
    if (Flag == true)
        doFooC()
    else
        doFooC2
</code>```

It seems there's multiple ways to "factor" this, such as 2 sets of if-elses, where one set handles when Flag == true.

Is there a "good way" to factor this, or perhaps when this if-else algorithm happens it usually means you  are doing something wrong?

答:
Well, there's always this ...

```<code>if variable == A && Flag
    doFooA()
else if variable == A
    doFooA2
else if variable == B && Flag
    doFooB()
else if variable == B
    doFooB2
else if variable == C && Flag
     doFooC()
else if variable == C
     doFooC2
</code>```

But frankly, I think the original code isn't half bad in the first place.

Body:
Well, there's always this ...

if variable == A && Flag
    doFooA()
else if variable == A
    doFooA2
else if variable == B && Flag
    doFooB()
else if variable == B
    doFooB2
else if variable == C && Flag
     doFooC()
else if variable == C
     doFooC2

But frankly, I think the original code isn't half bad in the first place.


答:
Multiple nested ifs increase the cyclomatic complexity of the code. Up to recently, having multiple exit points in a functions was cosidered bad structured code, but now, as long as the code is simple, and short, you can do so, making the code trivial to read:

```<code>    if (variable == A && Flag) {
        doFooA();
        return;
    }

    if (variable == A) {
        doFooA2();
        return;
    }

    if (variable == B && Flag){
        doFooB();
        return;
    }

    if (variable == B){
        doFooB2();
        return;
    }

    if (variable == C && Flag){
         doFooC();
         return;
    }

    if (variable == C){
         doFooC2();
    }

    return;
</code>```

Title: How to handle flag in multiple if-else's

Body:
I seem to see this often enough in my code and others. There's nothing about it that seems horribly wrong, but it annoys me as it looks like it can be done better. I suppose a case statement, might make a little more sense, but often variable is a type that does not work well or at all with case statements (depending on language)

```<code>If variable == A
    if (Flag == true)
        doFooA()
    else
        doFooA2

else if variable == B
    if (Flag == true)
        doFooB()
    else
        doFooB2
else if variable == C
    if (Flag == true)
        doFooC()
    else
        doFooC2
</code>```

It seems there's multiple ways to "factor" this, such as 2 sets of if-elses, where one set handles when Flag == true.

Is there a "good way" to factor this, or perhaps when this if-else algorithm happens it usually means you  are doing something wrong?

Body:
Multiple nested ifs increase the cyclomatic complexity of the code. Up to recently, having multiple exit points in a functions was cosidered bad structured code, but now, as long as the code is simple, and short, you can do so, making the code trivial to read:

    if (variable == A && Flag) {
        doFooA();
        return;
    }

    if (variable == A) {
        doFooA2();
        return;
    }

    if (variable == B && Flag){
        doFooB();
        return;
    }

    if (variable == B){
        doFooB2();
        return;
    }

    if (variable == C && Flag){
         doFooC();
         return;
    }

    if (variable == C){
         doFooC2();
    }

    return;


问:
sizeof style: sizeof(type) or sizeof variable?
I've seen two styles of using sizeof for memory-related operations (such as in memset or malloc):

sizeof(type), and

sizeof variable or sizeof(variable)

Which one would you prefer, or would you use a mix of the two styles, and when would you use each style? What are the pros and cons of each style and when you use them?

As an example, I can see the following pair of situations where one style helps and the other doesn't:

When you get the pointer indirection wrong:

```<code>type *var;
...
memset(var, 0, sizeof var);    /* oops */
</code>```

When the type changes:

```<code>new_type var;    /* changed from old_type to new_type */
...
memset(&var, 0, sizeof(old_type));    /* oops */
</code>```

答:
I would vastly prefer sizeof(type) over sizeof variable. Even though it forces you to worry more about the type and make more changes, it helps you avoid pointer indirection mistakes, which rank among the most common cause of bugs in C.

I would not worry so much about bugs where the type in sizeof(type) gets changed; whenever you change the type of a variable, you should do a quick scan to see where that variable is used and if you need to change any sizeof(type) statements. Even though there is always a chance of getting this wrong, it has a much lower risk than pointer indirection mistakes.

One advantage of sizeof variable is for arrays, but in practice I've found that passing arrays as pairs of first/len is much more common (in which case just use the length), plus it is also very easy to get the size wrong due to array/pointer decay, as in this example:

```<code>ID_INLINE mat3_t::mat3_t( float src[ 3 ][ 3 ] ) {
  memcpy( mat, src, sizeof( src ) );    /* NOT the same as 3*3*sizeof(float) */
}
</code>```

Body:
I would vastly prefer sizeof(type) over sizeof variable. Even though it forces you to worry more about the type and make more changes, it helps you avoid pointer indirection mistakes, which rank among the most common cause of bugs in C.

I would not worry so much about bugs where the type in sizeof(type) gets changed; whenever you change the type of a variable, you should do a quick scan to see where that variable is used and if you need to change any sizeof(type) statements. Even though there is always a chance of getting this wrong, it has a much lower risk than pointer indirection mistakes.

One advantage of sizeof variable is for arrays, but in practice I've found that passing arrays as pairs of first/len is much more common (in which case just use the length), plus it is also very easy to get the size wrong due to array/pointer decay, as in this example:

ID_INLINE mat3_t::mat3_t( float src[ 3 ][ 3 ] ) {
  memcpy( mat, src, sizeof( src ) );    /* NOT the same as 3*3*sizeof(float) */
}


答:
Depends on when you want to measure, you can use http://perfinsp.sourceforge.net/jprof.html
 in development to get a profile of your program. I've never use is, but I've used 'gprof' for non-java codes.

If you want to monitor your program in production, you can try http://newrelic.com. It gives you basically everything you mentioned and more but involve some cost. I think using it for a few months should help iron out most of the stuff that need to be fixed.

Both of them don't require any modification to your code.

Title: Easily add metrics to measure java code usability

Body:
I'm trying to create a process for better understand what's happening in my code. I want to create metrics to automatically give my answers about simple or complex questions like:

How many times a url was clicked? (how many requests arrived to a certain servlet method)

How many times a certain user requested the same page?

How many requests are pending in a queue on average?

and so on...

Is there an easy way to do this automatically and elegantly (for example - attribute like @CountHits would be great)?

I found this open source: http://metrics.codahale.com/getting-started/#reporting-via-jmx
But it's too coupled to the code. Not so elegant :/


问:
Keeping track of all objects of a class
I'm new to object-oriented programming, and I keep running into this issue. (I'm programming in Java) I've been a bit reluctant to ask about this, since it seems like such a basic issue, but I can't find any information on it, or questions about it here, and none of the textbooks I have read (on a quite basic level of course) have touched on this issue:

Often I need to keep track of all objects of a class that have been created, to iterate through them for various purposes. They way I currently write programs, many objects are only referenced from other objects, meaning I have no array or collection with which to reference them all.

I imagine that, as this seems like such a very basic necessity in OOP, there should be a quite institutionalized, and simple, way to go about this? Is it usual practice to keep a separate list of all the objects of a class?

I thought about a static array or collection, to which through its constructor, every new object created would be added. This however would not work with subclasses, since constructors are not inherited?

I realize this question might not have one easy answer; I just hope someone can enlighten me a bit on this subject. I feel like if I'm lacking a central piece of knowledge here.

答:
I don't know why you need to keep a list of all instances of a class.

That would cause memory leakage since those objects will never be disposed of, since the list will still be referencing them after no other class does.

But if you really want to follow that route:

Use the Factory pattern. A factory class with methods that instanciate the class and return the objects. That way you have a centralize point to control the instantiations.

Use the Singleton pattern to hold a list or lists that hold the instances.

Make the factory put each object of a certain type in a list after creating them.

By the way: constructors are inherited.

Title: Keeping track of all objects of a class


答:
I perfer sizeof(variable) over sizeof(type).  Consider:

```<code>int a1;
float a2;
memset(&a1,0,sizeof(a1));
memset(&a2,0,sizeof(a2));
</code>```

vs.

```<code>int a1;
float a2;
memset(&a1,0,sizeof(int));
memset(&a2,0,sizeof(float));
</code>```

In the first case, it's easy to verify that the right sizes are being passed to memset. In the second case, you need to constantly review top and bottom sections to make sure you are consistent.

Title: sizeof style: sizeof(type) or sizeof variable?

Body:
I've seen two styles of using sizeof for memory-related operations (such as in memset or malloc):

sizeof(type), and

sizeof variable or sizeof(variable)

Which one would you prefer, or would you use a mix of the two styles, and when would you use each style? What are the pros and cons of each style and when you use them?

As an example, I can see the following pair of situations where one style helps and the other doesn't:

When you get the pointer indirection wrong:

```<code>type *var;
...
memset(var, 0, sizeof var);    /* oops */
</code>```

When the type changes:

```<code>new_type var;    /* changed from old_type to new_type */
...
memset(&var, 0, sizeof(old_type));    /* oops */
</code>```

Body:
I perfer sizeof(variable) over sizeof(type).  Consider:

int a1;
float a2;
memset(&a1,0,sizeof(a1));
memset(&a2,0,sizeof(a2));

vs.

int a1;
float a2;
memset(&a1,0,sizeof(int));
memset(&a2,0,sizeof(float));

In the first case, it's easy to verify that the right sizes are being passed to memset. In the second case, you need to constantly review top and bottom sections to make sure you are consistent.


问:
Is knowing .NET only enough for a successful career in IT industry?

Possible Duplicate:

  Is it better to specialize in a single field I like, or expand into other fields to broaden my horizons?

Recently, I don’t know from where I got a thought in my mind that, “is knowing .NET development environment enough for a successful career in IT industry”. Should I be learning more languages too or will .NET suffice me for next 10-15 years.

By successful career I mean earning decent living and having good growth opportunities.

答:
If you refuse to learn anything else then it might (and only might) not be enough.

Now if you expand the question to "Is knowing Microsoft and .Net based technologies enough..." then the answer is a resounding yes! Depending.

I am approaching 20 years only knowing Microsoft (VB then .Net) technologies. Make a very good living and enjoy my job immensely. Look forward each day going to work and know there are many jobs out there that would hire me doing .Net/Microsoft platform development.

I feel no desire to learn any new platforms.

Then again I have no desire to get a different job. I like staying in the same small company that delivers very targeted and custom solutions to a diverse population.

I am not saying I will not ever learn a platform. May have to if all goes to hell. And I read Java/C++/LanguageWhatever books all the time. Don't understand much about the platform the book is about but the actual good ideas come across just fine. Effective Enterprise Java is one I go back to time and again. There are others.

I find it funny that so many who say something to the effect of "pre-optimization is the root of all evil" will also say you must pre-optimize your career.

Within .Net you can do procedural, OOP, functional, set based (sql) etc. etc.  Within .Net you can probably implement all the design patterns you could think of. Do P2P, Client Server, Web Whatever.0 etc. etc.

Would you be a better programmer if you learned a different platform/framework? Ehh, maybe but probably not. No research I know of says you will. So I am not going to waste my valuable time learning something I will probably never use and instead focus on learning what I need to make my customers and boss happy. That will probably be enough.


问:
Is it more efficient to learn as you go along with a project or to develop a broad base of programming skill?
For example, let's say I want to build a game, and I have a limited knowledge of programming(some but definitely not enough). Should my first move be to design the game and then learn how to implement each separate part? Or should you learn a language really well before you design a game?</p>

答:
Learning from experience is probably the most effective way to learn. And having a goal to focus your learning is likely also beneficial to your learning. Combining multiple styles of learning is even more effective, so this is not an 'either or' question.

If your goal is to learn; do both. Pick a goal (developing a game) and go for it. Along the way, you will need to improve your understanding of your tools and the language (using online or printed resources) to become more effective.


答:
Learning can be effective only when we apply (or at least know where to apply) what we learn. So, it will be a very intimidating and slow process to learn just to know more about any programming language.

But, it will be fun and fast if you learn while applying what you learn at the same time. If you wait until you learn a lot, you surely are wasting your time. Only when you do a project/application you will know its requirements and can do the programming counterpart to meet those requirements.

In your case, if you want to build a game application, first you need to decide which language and tool you are going to use in order to do that. Then get started with learning some basics like how to create a window, move an image, etc. and code alongside you learn. This i the most effective way of learning.

Title: Is it more efficient to learn as you go along with a project or to develop a broad base of programming skill?

Body: For example, let's say I want to build a game, and I have a limited knowledge of programming(some but definitely not enough). Should my first move be to design the game and then learn how to implement each separate part? Or should you learn a language really well before you design a game?</p>


答:
In my experience, learning along with a project has both pros and cons: The good things is that you are motivated to do something, you are learning and receiving some money for your job. The bad thing is that, at the beginning, you are going to feel some pressure because you are not proficient enough to do a good job and It is very easy to get stuck in a technology that you don't know or you don't understand.

My suggestions are:

try to allocate some time to learn the technology that you are going to use. It is totally understandable.

then try to start learning the technology before the project starts if possible

Don't use a technology poorly documented.

Always understand the theory behind the technology. This one is important because learning the theory will help you a lot to understand how you can get the most benefit of the technology and also you will understand when it is good to use it and it is not.

Have fun and learn from your mistakes.


答:
When making games people sometimes want a "self managing" collection of each type of game object.

One implementation looks like this:

```<code>public class Car {

    static ArrayList<Car> list = new ArrayList<Car>();

    public Car() {
        list.add(this);
    }

    void kill() {
        list.remove(this);
    }

    static public void updateAll()
    {
        for (int i = list.size() - 1; i >= 0; i--)
        {
                list.get(i).update();
        }
    }

    public void update()
    {
        //update logic
    }
}
</code>```

In this manner methods manipulating the collection can be declared static while non-static methods manipulate an instance (updateAll vs. update).

While fine for very simple scenarios, with even moderate complexity it is usually best to create separate manager classes.

Title: Keeping track of all objects of a class

Body:
I'm new to object-oriented programming, and I keep running into this issue. (I'm programming in Java) I've been a bit reluctant to ask about this, since it seems like such a basic issue, but I can't find any information on it, or questions about it here, and none of the textbooks I have read (on a quite basic level of course) have touched on this issue:

Often I need to keep track of all objects of a class that have been created, to iterate through them for various purposes. They way I currently write programs, many objects are only referenced from other objects, meaning I have no array or collection with which to reference them all.

I imagine that, as this seems like such a very basic necessity in OOP, there should be a quite institutionalized, and simple, way to go about this? Is it usual practice to keep a separate list of all the objects of a class?

I thought about a static array or collection, to which through its constructor, every new object created would be added. This however would not work with subclasses, since constructors are not inherited?

I realize this question might not have one easy answer; I just hope someone can enlighten me a bit on this subject. I feel like if I'm lacking a central piece of knowledge here.

Body:
When making games people sometimes want a "self managing" collection of each type of game object.

One implementation looks like this:

public class Car {

    static ArrayList<Car> list = new ArrayList<Car>();

    public Car() {
        list.add(this);
    }

    void kill() {
        list.remove(this);
    }

    static public void updateAll()
    {
        for (int i = list.size() - 1; i >= 0; i--)
        {
                list.get(i).update();
        }
    }

    public void update()
    {
        //update logic
    }
}

In this manner methods manipulating the collection can be declared static while non-static methods manipulate an instance (updateAll vs. update).

While fine for very simple scenarios, with even moderate complexity it is usually best to create separate manager classes.


答:
http://newrelic.com/ is a newish service that might help you.

It's essentially  a profiler with web-based display, and can show number of invokations per minute of a specific method. YMMV.


答:
The usual advice is to start with simple games and then slowly add complexity.
For example Pong then breakout or Space Invaders then Galaga. You don't have to do straight clones but mimicking a classic helps provide a clear recognisable target.

If you already know how to program (any language) then the next step is to build something.  You will encounter problems and they will be hard but you will learn a lot by solving them and no textbook or class can teach how to make the games you want to make anyway.

One other tip I will give is not to become too attached to any one language or environment.  The tools you use to make your first games will not be the ones you use later, but most of the skills will transfer.

Starting out on Game Programming


问:
Web Authentication using PKI Certs
I understand PKI reasonably well from a conceptual point of view - i.e. private keys/public keys - the math behind them, use of hash & encryption to sign a certificate, Digital Signing of Transactions or Documents etc. I have also worked on projects where openssl C libraries were used with certs for securing communication and authentication. I am also extremely familiar with openssl command line tools.

However, I have very little experience with web based PKI enabled projects & hence I am trying to design and code a personal project for understanding this better.

The requirements

This is the website for a bank. All Internet Banking users are allowed use any certificate issued by a few known CAs (verisign, Thawte, entrust etc). The Bank is not responsible for procuring certificates for the user. These certificates will be used for authentication to the banks website. The platforms/OS etc are still not fixed.

Design

I was wondering what's the best way to do authentication.

I saw that Apache has a way to enable 2 way ssl - in this case, i think navigating to the website would automatically ask for a cert from the user. But I am not sure if this is enough because it seems that all it verifies is whether a certificate is signed by a trusted CA & also may be whether it falls in a white list of subject lines of the certificates etc. But this is not enough for a bank case because you need to be able to associate a bankuserid with a certificate.

IIS seems to have a way by which I can have a certificate stored for each user in Active Directory. This is what I understood from reading few MSDN articles. You turn on 2 way SSL in IIS & then when the user tries to navigate to the website, IIS will send a request to the browser with a list of approved CAs and browser will let the user pick an appropriate certificate from his certstore and sends it to backend. I am assuming that IIS will do 2 things

Ensure that the user has the private key corresponding to the cert (by under the cover negotiations)

Based on the AD User-Cert Mapping, IIS will report the username to the application.

Do the authentication explicity by calling crypto functions rather depending on depending on the webserver to do it.

Show a user screen where he uploads a certificate and the application ensures the user has the private key corresponding to the cert (by asking the front-end to sign some string using the cert).

The application has a database some of data is stored which allows each user to be mapped to his userid. This may be

the whole cert corresponding to each userid

the CA and cert serial number corresponding to each user id.

I was wondering which is the commonly used method? What are the best practices?
If I should go with #3, what are the best ways to do this?

Something which can also easily work with smartphone apps will be an added bonus.

Update

Let me clarify my statement "code the authentication part myself" because some of the answers seem to indicate that it has been misunderstood - my bad for not being clear.

This doesn't mean I write crypto stuff myself. It just means I will actually call crypto routines explicitly instead of depending on IIS or any other webserver do it implicitly.

答:
Personal certificates work well for periodical renewal of certificates (which has quite a robust process behind it) and can be implemented as a "password-less" authentication that customers like

but where it fails is

The cost per certificate

compatibility with modern browsers

end users extracting certificates and storing private keys insecurely

be aware that modern personal certificates with sha-2 signing do not work with Safari on iPad and lots of modern browsers.  This is because personal certificates never really took off like the certification authority organisations thought it might.  Issuing 30,000 certificates (what we do) costs about the same per certificate as some hardware token types.

Your strategy to allow customers to find their own certificates is not really valid.  It's hard to find suppliers of personal certificates nowadays and they are quite expensive - you need to ensure that the business case works otherwise customers will simply not buy into this.

Title: Web Authentication using PKI Certs

OwnerDisplayName: Callum Wilson


答:
Okay, a lot going on here.  First things first, client cert authentication is useless if it isn't supported on the endpoint.  So, we have a great post from Intrepidus covering the basics of client authentication for smartphone apps.

Next, let me highly suggest you not code your own authentication routine.  There are lots of great, vetted libraries that handle this.  You'll save yourself functionality and security bugs by running with a mature library for auth.  Using a vetted, mature library for this would definitely be best practice.

Next best practice is using a directory for handling your client:certificate mapping.  So you'll be looking at AD or LDAP.  As you mentioned, Windows and IIS makes this pretty seamless for you.  IIS.net has a good rundown on configuring certificate mapping under IIS.

If you roll with Apache, this isn't as easy out of the box.  It looks like mod_authz_ldap does client certificate mapping, but I've not personally worked with it.

So that brings us to the logistics of actually implementing something like this.  You are not signing the users' certs, so you need an ironclad process for a user submitting their cert and having your app publish it into the directory.  I would want to see two-factor for this, with a password auth and a text message or call to a trusted number.  I would email the user to let them know that a cert was added to their account.  I would let a user remove the user-cert mapping through their account management page in the app.

I would look at what Google and Facebook do for setting cookies for trusted devices to avoid two-factor.  I would have new devices auth with two-factor before allowing certificate-only auth.

I would also think about how to handle user certs being revoked.  This means checking an external certificate revocation list (CRL).  What do you do if a client certificate doesn't have a CRL distribution point defined?  Do you check the CRL whenever the user logs in, or on a scheduled basis as part of a job, since there will likely only be a handful of CRLs in use?

Really, this boils down to: how do I know I can trust that the users' certs have not been compromised, and how do I trust that I can map certificate X to user Y.

Title: Web Authentication using PKI Certs

Body:
I understand PKI reasonably well from a conceptual point of view - i.e. private keys/public keys - the math behind them, use of hash & encryption to sign a certificate, Digital Signing of Transactions or Documents etc. I have also worked on projects where openssl C libraries were used with certs for securing communication and authentication. I am also extremely familiar with openssl command line tools.

However, I have very little experience with web based PKI enabled projects & hence I am trying to design and code a personal project for understanding this better.

The requirements

This is the website for a bank. All Internet Banking users are allowed use any certificate issued by a few known CAs (verisign, Thawte, entrust etc). The Bank is not responsible for procuring certificates for the user. These certificates will be used for authentication to the banks website. The platforms/OS etc are still not fixed.

Design

I was wondering what's the best way to do authentication.

I saw that Apache has a way to enable 2 way ssl - in this case, i think navigating to the website would automatically ask for a cert from the user. But I am not sure if this is enough because it seems that all it verifies is whether a certificate is signed by a trusted CA & also may be whether it falls in a white list of subject lines of the certificates etc. But this is not enough for a bank case because you need to be able to associate a bankuserid with a certificate.

IIS seems to have a way by which I can have a certificate stored for each user in Active Directory. This is what I understood from reading few MSDN articles. You turn on 2 way SSL in IIS & then when the user tries to navigate to the website, IIS will send a request to the browser with a list of approved CAs and browser will let the user pick an appropriate certificate from his certstore and sends it to backend. I am assuming that IIS will do 2 things

Ensure that the user has the private key corresponding to the cert (by under the cover negotiations)

Based on the AD User-Cert Mapping, IIS will report the username to the application.

Do the authentication explicity by calling crypto functions rather depending on depending on the webserver to do it.

Show a user screen where he uploads a certificate and the application ensures the user has the private key corresponding to the cert (by asking the front-end to sign some string using the cert).

The application has a database some of data is stored which allows each user to be mapped to his userid. This may be

the whole cert corresponding to each userid

the CA and cert serial number corresponding to each user id.

I was wondering which is the commonly used method? What are the best practices?
If I should go with #3, what are the best ways to do this?

Something which can also easily work with smartphone apps will be an added bonus.

Update

Let me clarify my statement "code the authentication part myself" because some of the answers seem to indicate that it has been misunderstood - my bad for not being clear.

This doesn't mean I write crypto stuff myself. It just means I will actually call crypto routines explicitly instead of depending on IIS or any other webserver do it implicitly.

OwnerDisplayName: Brandon Franklin


答:
While I really wanted to answer issue by issue, I think I'll hit this topic by topic:

Authorization/Authentication

OK, first things first.  For your example, you need both:

Authentication - proof that the user is who he says he is.  You've choosen PKI, with the implied proof of private key as your authentication.

Authorization - connection of the user to what he is allowed to do. This is the connection point between logging in and getting access to the allowed accounts.  The mapping of certificate to account and account access capabilities is the authorization.

Authorization-wise, you have the problem of figuring out the process by which you connect your user's subject DN to their bank account.  Given the gravity of the transaction, you definitely want to have a strong process for this, and there is no single right way here.  You'd have to consult with the bank, and probably it's lawyers, to figure out how to do this in accordance with policy.

SSL, Client/Server Authentication, Proof of Private Key

The SSL protocol always includes server authentication, with an additional optional setting for client side authorization.  You are right with #1 in that Apache offers a setting that adds Client Authentication by PKI, and you can provision it with a list of trusted CAs.  During the setup of an SSL session that requires Client Authentication via PKI - you will get a proof of private key.

Either option #1 or option #2 will provide this - both Apache and IIS can be configured this way.  Best practice wise, I'd take either one over rolling your own solution.  #3 comes periliously close to the "don't write your own crypto" rule.  Assuming that you can tie your transaction to the presence of an authenticated SSL session, there is no reason to roll your own.

Also - in either option #1 or option #2, there is a way to get your hands on the whole certificate, and from there, to any part of the certificate.  Typically Subject DN and/or certificate serial number are used to determine the user's identity for authorization purposes.

In terms of "common usage" - all major web servers are pretty common.  IIS, Apache, Tomcat, and many others can be configured with client auth SSL.  The decision from there is largely based on overall implementation.  The major web servers have all had ways to get access to the certificate provided in the SSL session, which is what you need for more detailed verification.

Certificate Verification Add Ons

At a minimum, you'll need to:

setup an SSL session

pull the certificate (most web server's will check the certicate's signature and proof of private key)

verify the certificate's validity date (not a given with any webserver)

perform the authorization check for which accounts this certificate can access

Given the high stakes of banking, you may also want to verify the certificate's revocation status - if the user's private key is lost or stolen, their certificate should be revoked.

IIS may have the hooks for an OCSP or CRL verification - it tends to be a more comprehensive (hand holding!) type of system, but I don't remember off the top of my head.  I also don't remember if it's going to force you to use Microsoft products for this.  For Apache, you would almost certainly have to code or add on an OCSP/CRL check.  I believe it has hooks during SSL session establishment - usually this check performed once when the SSL session is set up.

Authorization

On #1 vs. #2 - you're right that IIS has some built in functionality that'll tie the cert provided in the SSL session to an AD repository.  It's one of the cases where Microsoft goes the extra mile to make it easy to buy and use more of it's products. :)  There are nuances to how IIS ties into AD that are beyond the scope of this question and beyond my immediate recollection.  I've done some pretty crazy stuff with IIS and AD, and my general thought is that while you are doing something as relatively simple as pulling the username based on the certificate from an AD repository - you're probably fine.  It's when you get into more complex issues of data storage, odd AD lookups, and particularly crazy (but legitimate) things with PKI, you'll find that the excessive handholding provided by IIS is more like hand cuffs than a helping hand.

With IIS, even still - you'll need something added to your AD structure, or somewhere else, tying the username to the bank account.  Typically in banking, a user has multiple accounts.  And 2 users can have a joint account, so this is a many to many relationship.

For #1 - yep, you need to write your own lookup.  You need to code:
- a database or LDAP hierarchy connecting the certificate to the user and the user to the user bank accounts.  The guaranteed unique part of a certificate is serial number + issuer DN.  Often Subject DN will work, but its not guaranteed in all PKI systems.

That's typically how developers using PKI for high end authentication with Apache do it.  Having worked in a number of these systems, I have yet to encounter a case of easy authorization reuse, so I never really see it as a huge minus - I'm going to have to have something specialized either way, as roles/privileges are never easy.

This sounds like a mix of #1 and #3 - my strong advice would be - use the native capabilities of whatever application/web server you use to generate the SSL session.  That'll let the browser to server setup with the certificate query take place in the standard, best practice, way.  From there, with Apache, you'll need to roll you own authorization system.  IIS will provide Microsoft's idea of how this should work for you.

Known Gotchas

Do a bunch of browser testing.  From year to year, browser to browser, I find gotchas with SSL session handling.  Correctly chaining the SSL session to the series of web page requests and making sure that logout is handled correctly are the biggest areas of concern.  And it's got a lot to do with both the server and the browser software.  SSL is stable enough that when it works, it usually works, although there can be IE vs. everyone else issues.

In particular, the last time I did this, the question of force coding and session time out was a big deal.

Smart Phones

Good.  Luck.  is about all I can say. I'm not at all a mobile app developer, but my impression thus far is that in the average smart phone, PKI cert handling is sub par or non-existant.

I would so love to be proven wrong.

Title: Web Authentication using PKI Certs

OwnerDisplayName: bethlakshmi


问:
Adding explicit interfaces to Legacy managed C++ code
I have a bit of a challenge and I am not sure how to approach this.
We have a very very large project (that is about 5 years old).
The code base is HUGE so a full refactor is out of the question.

What we will be doing is refactoring bits of code as we use those parts (this is backend code, which we will be using on a frontend system)

The existing code has got zero abstraction, and we want to build unit tests for it. We use the RhinoMock framework and the call from my superiors are that we need to add explicit interfaces to the code, thereby abstracting it so that we can mock the objects in RhinoMock.

I have one broader and one narrower question:
1) Is an explicit interface the best option? Or should I suggest some other technique...

2) Can anyone suggest a high-level approach to this type of code refactoring? I've never been in a position where I have had to add explicit interfaces to existing code. (The legacy code is Managed C++ by the way)

Thanks in advance for your answers. Also, if this question is in the wrong place or too broad, I do apologize.

答:
This is one thing that annoys me about unit test frameworks - you have to change the way you code, just so you can use the unit test framework.

There are others - cppunit for example does not require interfaces inserted everywhere which, for a legacy codebase in C++, might be a better solution.

The other alternative is to split chunks of code away from the massive codebase and reimplement them as separate projects, then refactor those in isolation.

Of course, you could just say unit testing a legacy codebase is too hard,and you should spend your efforts on automated integration testing instead. That's the way testing used to be done, and still should be used heavily even with unit-test-enabled codebases.


问:
Sync SQLite using only HTTP
I currently have a SQLite DB on my server that is needed by an android app I am currently developing. I download the DB to the android device using HTTP each time the contents are changed.

Does anyone have any suggestions as to how to do this more efficient. ie. when the database gets large I don't want the android user to have to download the whole database again just because one record was added.

答:
I don't think there's a good off-the-shelf solution at the database level. The way would approach this is roughly this:

The database schema includes versioning information; this can be as simple as created/modified timestamps on each row, or you can fully historize everything, depending on your practical needs. The key here is that you need to be able to check what the changes were after a given date/time.

The server exposes data through a web service; since all you need here is basic CRUD, a RESTful API would be appropriate. The API should expose a way of querying for changes, e.g. http://example.com/api/modifications/things?refdate=20130601 would give you all the modifications to the things table since 06/01/2013.

The client app would use API calls to download recent changes from the server, and push local changes back up. It would run its own sqlite database locally, but you'd never exchange the database files directly.

So instead of pushing the entire database back and forth, you selectively push and pull just the changes, with the API acting as the interface.

OwnerDisplayName: Keagan Ladds

Title: Sync SQLite using only HTTP


答:
No, you can't change the class of an object once instantiated, at least not in any programming language I know of. The reason is that this would blow up all sorts of guarantees a class hierarchy would otherwise give you; not to mention that "changing the class of an object" is a highly undefined requirement - how do you migrate the object's state? How do you map fields from one class to the other?

Considering your problem at hand; you have fallen prey to the seduction of naive polymorphism and reuse-by-inheritance. While both a Car and a Truck are vehicles, it is not very wise to have them inherit from Vehicle directly and encode all the behavior in these three classes. In other news, the textbook is wrong.

Instead, split the functionality into components. A Vehicle has a license plate, and a type. The type determines whether it is a car or a truck. You can then swap out the vehicle's type without changing its base properties.

Also, note that you are probably lying about your data. You create a Vehicle object without actually having a vehicle at hand; all you want is store the license plate number. So maybe putting the license plate into its own class, and linking it to an actual vehicle later might be a better design choice.

Title: OOP concept: is it possible to update the class of an instantiated object?

Body:
I am trying to write a simple program that should allow a user to save and display sets of heterogeneous, but somehow related data. For clarity sake, I will use a representative example of vehicles. The program flow is like this:

The program creates a Garage object, which is basically a class that can contain a list of vehicles objects

Then the users creates Vehicles objects, these Vehicles each have a property, lets say License Plate Nr. Once created, the Vehicle object get added to a list within the Garage object

--Later on--, the user can specify that a given Vehicle object is in fact a Car object or a Truck object (thus giving access to some specific attributes such as Number of seats for the Car, or Cargo weight for the truck)

At first sight, this might look like an OOP textbook question involving a base class and inheritance, but the problem is more subtle because at the object creation time (and until the user decides to give more info), the computer doesn't know the exact Vehicle type.

Hence my question: how would you proceed to implement this program flow? Is OOP the way to go?

Just to give an initial answer, here is what I've came up until now. There is only one Vehicle class and the various properties/values are handled by the main program (not the class) through a dictionary. However, I'm pretty sure that there must be a more elegant solution (I'm developing using VB.net):

```<code>Public Class Garage
    Public GarageAdress As String
    Private _ListGarageVehicles As New List(Of Vehicles)

    Public Sub AddVehicle(Vehicle As Vehicles)
        _ListGarageVehicles.Add(Vehicle)
    End Sub
End Class

Public Class Vehicles
    Public LicensePlateNumber As String
    Public Enum VehicleTypes
        Generic = 0
        Car = 1
        Truck = 2
    End Enum
    Public VehicleType As VehicleTypes
    Public DictVehicleProperties As New Dictionary(Of String, String)
End Class
</code>```

NOTE that in the example above the public/private modifiers do not necessarily reflect the original code


答:
If you both are going to work on a shared codebase, the only sensible way is to use a language you both master.

The best option, by far, is to learn each others' language. Not only will this give you two shared languages to work with (which means you can choose the most appropriate one for the job at hand), learning new languages is essential to becoming a versatile developer with an eye for the big picture and a nice big toolbox full of alternatives to pick from.

Another option is to both learn a third language. This is especially interesting when neither language is a good fit for whatever it is you're going to build: both PHP and C# have some serious downsides, and it might just turn out that, say, Python could be the best language for your project. Again, learning a new programming language is always a good investment, even if you end up not using it.

A third option would be to strictly split up the codebase into a C# part and a PHP part, and define language-agnostic interfaces between them. For example, you could have a C# front-end that talks to a PHP server over a RESTful API. This is seldom a good choice, though, and it will make your team structure overly rigid: you can't just jump in and help with the other half of the project, because it's in a language you don't know. It also means the both of you will have a huge bus factor, so I suggest you don't do this.

TL;DR: Just get your act together and learn each other's language.


问:
How do you balance out code structuring (few big functions vs. many small ones)?
The golden rule of code structuring is always said as splitting into many sub functions is a good thing. Though I noticed it becomes a problem in complex applications when a class of e.g. 10 bigger functions is split into a class with 50 functions. When development went so far, it becomes quite hard to understand the concept of the class, I mean you lose survey. This is often the case when you look into code of others or in your own code after some months past.

I've heard a function should not be bigger than what fits on the screen. And then you start to split into sub functions, and the following effect is a class of many functions where you lose survey.

One example: The Qt library internally uses private classes, which means every class has a d pointer to a private object of its own private class containing all those helper functions moved out to it.

Sometimes I also wished I could colour the background of the important code.

So what's your approach of keeping complex code structured but still understandable?

答:
If you Feel Like it Could Be Splitted, Split It!

I don't really think of the balance as you seem to be considering it now: if it's bigger than 25 or 30 lines, and if I cannot get it almost instantly, then it can be refactored into smaller functions. Especially for big "torrent" functions that tend to be very imperatively written.

Use Descriptive Coding Conventions

Yes, the reader will need to jump through more hoops to understand the code, but if the functions are aptly named, it's an help. It's also an help if you get a stacktrace, as it gives you a semantic hint on what was happening.

Visual Aids

Sometimes I also wished I could colour the background of the important code.

Quite often, it's likely the "unimportant" code that's mostly internal and that you can separate into smaller functions can be put into private methods or extracted to utility classes.

While it has some disadvantages too (testing, coupling, etc...), it can help to quickly visually separate them from the rest, especially if you can change your code highlighting rules based on the access modifiers.


问:
Auto functions in c++
I'm not so familiar with C++. Can someone please inform me what this lines does (in detail):

```<code>auto add_element = [&rows,&cols,&values](size_t row, size_t col, double value)
{
    rows.push_back(int(row));
    cols.push_back(int(col));
    values.push_back(value);
};
</code>```

Rows, cols, values are obvious vectors.

Is this the same as void add_element(vector & rows, size_t row, .....)

答:
That defines and stores a lambda. Read here on more details or google up on C++11 and lambda.

One of the most exciting features of C++11 is ability to create lambda functions (sometimes referred to as closures). What does this mean? A lambda function is a function that you can write inline in your source code (usually to pass in to another function, similar to the idea of a functor or function pointer). With lambda, creating quick functions has become much easier, and this means that not only can you start using lambda when you'd previously have needed to write a separate named function, but you can start writing more code that relies on the ability to create quick-and-easy functions. In this article, I'll first explain why lambda is great--with some examples--and then I'll walk through all of the details of what you can do with lambda...

Title: Auto functions in c++


答:
The canonical answer is to apply the Single Responsibility principle:

the single responsibility principle states that every class should have a single responsibility, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility.

Also, classes must have Cohesion

cohesion refers to the degree to which the elements of a module belong together. Thus, it is a measure of how strongly-related each piece of functionality expressed by the source code of a software module is

On the other hands, symptoms of low cohesion are exactly what you describe:

Disadvantages of low cohesion (or “weak cohesion”) are:

Increased difficulty in understanding modules.

Increased difficulty in maintaining a system, because logical changes in the domain affect multiple modules, and because changes in one module require changes in related modules.

Increased difficulty in reusing a module because most applications won’t need the random set of operations provided by a module.

As such, my advice is to review your class structure and refactor appropriately. You don't need to have very large classes, but certainly you want classes that do one clear thing right.

Title: How do you balance out code structuring (few big functions vs. many small ones)?

Body:
The golden rule of code structuring is always said as splitting into many sub functions is a good thing. Though I noticed it becomes a problem in complex applications when a class of e.g. 10 bigger functions is split into a class with 50 functions. When development went so far, it becomes quite hard to understand the concept of the class, I mean you lose survey. This is often the case when you look into code of others or in your own code after some months past.

I've heard a function should not be bigger than what fits on the screen. And then you start to split into sub functions, and the following effect is a class of many functions where you lose survey.

One example: The Qt library internally uses private classes, which means every class has a d pointer to a private object of its own private class containing all those helper functions moved out to it.

Sometimes I also wished I could colour the background of the important code.

So what's your approach of keeping complex code structured but still understandable?


答:
The aim is to remove redundancy. If you use sizeof for an operation related to a variable, then obviously you shall reflect that in the sizeof.  Yes, you can mess up like in the first example, but the cure is not use type, but *var, correctly matching the aim.

To mitigate such problems it's usual to use macros, templates and similar tools trained for the use case rather than naked sizeof.

See my CLEAR macro that is used exclusively instead of naked memset. Saved my ass several times in cases of indirection typo or when a struct content picked up a vector or  string...


问:
Splitting user stories into smaller stories
I've been reading various techniques for splitting large user stories in helpful ways, such as by user workflow through the system etc. What I'm struggling with is how to word these smaller stories if all they achieve is facilitating the next step in the process and not delivering the application's main benefit to the user.

For example, if my new system is split down into 3 smaller stories along the lines of;

Create a new account online

Create certain entities against my new online account

Have my mobile device query these entities against my account and act on them

The system only really provides useful functionality to the end user when all stories are complete. So if following the traditional "As a [User] I would like [Functionality] so I can [Benefit]" The benefit of the first and second story is simply facilitating subsequent stories and not really providing the user with the main piece of functionality (the epic). Is this the correct way to do this?

答: The best way then would be to treat it as an epic, and scope in stories in sprints thereafter. My answer uses the same approach (stories as part of an epic).</p>


问:
Why the current enthusiasm for Functional Programming?
I've been hearing a lot of enthusiasm about functional programming languages lately, with regards to Scala, Clojure, and F#.  I've recently started studying Haskell, to learn the FP paradigm.

I love it, it's really fun, and fits my math background.

But will it ever really matter?  Obviously, it's hardly a new idea.

Here's my questions:

What has contributed to the recent FP enthusiasm?  Is is merely boredom with OO, or has something changed to make FP more needed than before?

Is this indicative of a FP future?  Or is this a fad, like object orient databases?

In other words, can anyone help me understand where this comes from and where it might be going?

答:
Here's my questions:
  1. What has contributed to the recent FP enthusiasm? Is is merely boredom with OO, or has something changed to make FP more needed than before?
  2. Is this indicative of a FP future? Or is this a fad, like object orient databases?

Others have given good technical reason.

I think the main reason FP is gaining traction among the average developer and manager types is it's promise to allow better use of multi-core CPUs. From everything I have read FP allows easier (not easy) parallel programming.

It's future widespread use will be if the promise is real and is fulfilled.


答:
So what's your approach of keeping complex code structured but still understandable?

My approach is to build several abstraction layers and have each component of each layer contain at most n elements from the lower layer, where n is a relatively small number (between 5 and 20) beyond which I lose the overview of the structure of a component. I cannot name an exact number but I would say 20 is already in the "too large" area for me. If you can keep more stuff in your mind, your number may be higher.

As an example, consider the 6 layers: system, subsystem, module, class, method, line of code. The names are chosen a bit arbitrarily, but it should give the idea. Also, let n = 10.

Take a module: it can have at most 10 classes (to be more flexible, let's say it can also have 12 or 15 classes, but definitely not 50 classes!).
Apply the same principle to all layers: if a method has more than 10 lines it is doing too much, try to split it. If a class has more than 10 methods: split it. Etc.

With this scheme, you can organize roughly 10^5 = 100000 lines of code. Still, if you look down from a higher layer to a lower one, you still see some component that has at most 10 sub-items. If your project is larger, you can add extra abstraction layers.

The main idea is to split items that are too large to be understood and to push the complexity to the upper abstraction layers until you have enough abstraction layers to manage the complexity of the whole project.


答:
I would use a different design where garage contains a list of parkingspace objects.
The parkingspace object would implement the interface Licensplate.

Now I would have the vehicle object also implement the licensplate interface.

That way you can instantiate your list of parkingspaces, with corrensponding licenseplate numbers and instantiate your cars and trucks later with licensplates.


答: Depending on the purpose sizeof(variable) could be the best solution. In that way, you can change your variable type if necessary, without correcting all entries for the type. But again, it depends on your objective.</p>