问:
Why do people disable JavaScript?
I asked a question yesterday Should I Bother to Develop For JavaScript Disabled?. I think the consencus is: Yes, I should develop for JavaScript Disabled. Now I just want to understand why users disable JS. It seems many developers (I guess people who answered the questions are developers) disable JS. Why is that. Why do users disable JS? For security? Speed? or what?</p>

答:
Because browsers used to have slow JavaScript implementations and too many n00b web designers just used it for irrelevant things like button rollovers.

On a fast machine, with a modern browser, nobody in their right mind disables it all the time.  Which is not to say there aren't plenty of very "security conscious" people and others without the funds, desire, or know-how to be running a modern browser on a fast computer...  It was only recently that IE6 stopped being the most popular browser on the internet!

Title: Why do people disable JavaScript?


问:
What is a good design pattern for multi-mode software?
I will explain my question by way of example, but I'd love a general solution.

I am writing a JavaScript application that needs to function differently depending on its run-time context. To handle this, I have have done the following. (1) At the beginning of the program, I set two context variables—let's say is_foo and is_bar, which can't both be true. Then (2) throughout the code, I check these variables whenever I need to account for the context:

```<code>if (is_foo) {
    app.do_something(is_foo_config);
} else if (is_bar) {
    app.do_something(is_bar_config);
}
</code>```

Are there any good design patterns or best practices for designing a program that has a "mode" with related configurations?

答:
Since the mode is selected at startup1 the Strategy pattern would work.

Related is the Replace Conditional with Polymorphism (also here) and Replace Type Code with State/Strategy refactoring.

1 If the mode were changing during the course of execution, then the State pattern would be called for.  It's similar to the Strategy pattern and has similar inner workings.

ContentLicense: CC BY-SA 3.0


问:
How to deal with clients that only gives you huge flow of "how to do this", but can't say "what and why" they need?
Sometimes I have clients that from start gives you huge flow of words about "how task should be done in details", like "you must use SQL Server here", "should do this in do-while-loop", "should make two functions like that, and they should run in parallel", etc..

But they never-ever give you any word about "what is this task about?" and "why it's needed?". Even if you ask them about this questions directly, they only can say "I don't know, but this work should be done".

Doing this jobs is realty hard and despairing, because you don't understand project as part of some system - there is no system yet, and maybe never be.

Is there any way that can help deal with this kind of clients?

答:
Fire them.  Refer them to your worst enemy.  You don't need the headaches.  If they don't know what they want, neither will you, and the amount of trouble you will go through, finding out what is needed, IS NOT WORTH whatever they're planning on paying you.

Many years ago, a drinking buddy of mine gave me a piece of wisdom.  When considering undertaking any project, ask three questions:

What is the problem we are trying to solve?

What are the deliverables?

How will I know I am finished?

If the potential client cannot give clear, cogent, complete answers to ALL THREE questions, neither he nor you are ready to start work on the project.  ANY work you put into it at this point must be directed at answering those three questions, AND NO MORE.


答:
Even if you ask them about this questions directly, they only can say "I don't know, but this work should be done".

Your job is now to explain to them why you need that information. As far as s/he is concerned, you don't need to know, you just need to do what they say.

You need to explain that if you know why all of this needs to get done, you will be able to come up with the solution better and faster. Everyone will be happy :)

Remember though that the person may not know the answer... in that case there is some weird politics going on!

Title: How to deal with clients that only gives you huge flow of "how to do this", but can't say "what and why" they need?

Body:
Sometimes I have clients that from start gives you huge flow of words about "how task should be done in details", like "you must use SQL Server here", "should do this in do-while-loop", "should make two functions like that, and they should run in parallel", etc..

But they never-ever give you any word about "what is this task about?" and "why it's needed?". Even if you ask them about this questions directly, they only can say "I don't know, but this work should be done".

Doing this jobs is realty hard and despairing, because you don't understand project as part of some system - there is no system yet, and maybe never be.

Is there any way that can help deal with this kind of clients?


问:
Is it reasonable for a client to expect automated test scripts as project deliverables?
Our company is currently halfway through a software project with a consulting firm. As someone who will be taking ownership of the project after the consultants finish, is it reasonable for our company to ask the consultants to write automated test scripts and pass them on to us?</p>

答:
It is reasonable to negotiate for having automated test scripts as a deliverable, but it is not reasonable to expect to get them if they were not explicitly included in the (initial) agreement.

Unless the project is explicitly being executed under a development method that implies automated testing, such as TDD, or you negotiated for delivery of the scripts up front, you can't presume that the consultancy firm is using (or even creating) scripts for automated testing.

If you realize at a later date that you would like to have such scripts as a deliverable, you must negotiate a change to the project scope with the consultancy firm and accept that this will likely have an impact on the schedule and the costs of the project.


答:
I am not a web developer, and I have only a moderate understanding of the way the internet works. So this is an answer from a user.

My experience leads me to believe many sites are simply poorly coded, whether out of laziness or ignorance: When I would view a basically static web page, such as a Facebook page, my CPU usage would increase by something like 15%, and drastically more with multiple tabs. Eventually it got to the point where I would have to wait for a response after clicking a button or link and my CPU would overheat and lock up.

On many of these worst offenders (sites), nothing visible is changing and nothing interactive is happening. I could only suppose the site's code was constantly making excessive refreshes, polls, and endless loops.

This drove me to install NoScript to free my CPU usage and stop browsing from becoming a frustrating chore.

The other wonderful add-on I use is FlashBlock.

ContentLicense: CC BY-SA 2.5

Title: Why do people disable JavaScript?

Body: I asked a question yesterday Should I Bother to Develop For JavaScript Disabled?. I think the consencus is: Yes, I should develop for JavaScript Disabled. Now I just want to understand why users disable JS. It seems many developers (I guess people who answered the questions are developers) disable JS. Why is that. Why do users disable JS? For security? Speed? or what?</p>


答:
Ask them

How will we know when the work is finished?

How will you decide whether to pay me?


问:
Store an object's name in the object or externally?
I'm in the process of building an application which needs extensive logging of points in time at which certain events happen. For example when it renders a sequence of different shapes to the screen then we need a logfile with info like 'shape A rendered to surface at time X, shape B rendered to surface at time Y, surface flipped at time C' etc. in response to comments These names (A,B) should be meaningful and will either be user-defined (e.g. 'MyGroupOfRectangles') or automatically generated (like shape type + number, e.g. 'Rectangle1' or for bitmaps/avis/... use the filename). Main reason for this is that most of the time the logfile is going to be interpreted simply by the user reading it and quickly checking out if the sequence is doing what he/she wants to.

In order to make this happen it's clear that at the moment the log function is invoked it needs to know the name of the shape it's going to log about. One could just give any type of object which is going to be logged about a string member. However thinking about that there are some implementation- and design-wise questions which make me doubt that approach. But other approaches in turn have other problems.

The major question being (almost philosophical - I'm probably overthinking this): should an object know it's own name? After all it's merely an implementation detail here, used solely for logging - if I wouldn't want to log Shapes by their name they wouldn't need to be named at all.

So does it make sense to stuff the name in there as well, or would it be a better practice to keep a map somewhere which links object instances to a name? Something like

```<code>Map< Shape, string > shapeNames;

string NameForShape( Shape s )
{
  return shapeNames.Contains( s ) ? shapeNames[ s ] : "<unnamed>";
}
</code>```

This is very much unintrusive but does introduces some other potential problems in keeping the map up to date with existing shapes: should a shape be destructed, it's name also has to be erased from the map.

The other option (or if there are multiple other options, by all means let me know) is to make a Shape returns it's name. Being an interface it could be like this:

```<code>interface Shape
{
  void Render();
  ...
  string Name();
}
</code>```

However this means every implementation has to take care of providing the Name() implementation and they're likely to going to be doing that all in the same way, like

```<code>class Rect : Shape
{
public:
  Rect( string name ) : { this->name = name; }

  string Name() { return name; }

private:
  string name;
}
</code>```

That's quite some boilerplate and DRY is a holy rule so raises more questions: do I get rid of the pure interface and make it abstract instead (not ideal for unit testing)? Or do I add an extra layer with a default Shape implementation like NamedShape which partially implements Shape and just provides Name() (extra inheritance layer is not ideal either)?

答:
What you'd like to have is a mixin, or a trait, but you can't have it since your language of choice doesn't support it. So you are looking for ways to emulate it.

Personally I agree that deriving an object's name shouldn't be its own responsibility. For one, because if your naming convention changes, you have to change your Rect.Name implementation. So now the Rect class an extra reason to change, which violates SRP.

Custom implementation of Object.toString - brought up by @gnat in comments - can be tremendously helpful for debugging, but - perhaps it's just my bias - I wouldn't put anything actually important, any data worth of being persisted, into toString.

Transferring the responsibility of naming objects in a clear manner into a class of its own sounds like a good idea.

Does it really have to keep track of every shape in existence, though? That's what worries you, and I'm not sure why that would be a requirement.

Couldn't this class simply derive reasonable names for any given Shape on the fly? I may be missing some context here. You always know what type any particular Shape instance is. Where are the A, B, C identifiers coming from?


问:
Freelance web development vs. design
Do web design freelancers (I'm thinking individuals, not companies) typically do all development and design work themselves? What are the options for those with a strong base in back-end web development but less with web design, color schemes, layouts, graphic design, etc.?

答:
Some people do try and do both.. and in most cases I have seen they do one well and the other... not so much.  Designing and Programming generally take two different types of people.  Often I've seen designers subcontract the programming work and focus on the designing aspects.

Personally I consider myself formost a programmer.  I understand the basic aspects of designing web pages but I would rather let somone else deal with those details.

Title: Freelance web development vs. design


问:
Software to access GSM Terminal, sending and receiving AT commands, validating results
I am currently implementing a software that uses a GSM terminal to perform actions. Actions can be sending messages, checking balance, receiving status report messages, setting the pin, ...

The communication between terminal and program runs over a serial port. I am sending AT commands (basically strings) to the device that executes them and returns a message depending on the command. I have a limited set of about 20 different commands that need to be executed and some of them have the same return messages (just OK or ERROR). While waiting for a return value is it possible that an incoming message notification is returned instead and the actual value the program is waiting for arrives later.

I need to consider that in the future the GSM terminal shall be exchangeable easily. The AT command set is  mostly standardized, but the return values can differ between manufacturers and even mobile operators...

I am struggling to find a good generic design concept. The tasks to be performed are the following:

Check if response belongs to the command sent

Check if response is valid (command worked or not)

The rest of the system is running well (reliable sending and receiving, timeouts, retransmit in case of errors, etc...), it's just about verifying return values that can happen to belong to several commands sent.

I am using an event based observer system. Every time a return value is received it is published to all subscribers which will process the result. Before sending a command to the serial interface, a component registers with the observer and unregisters if its job is done. But if I have two subscribers that wait for a result and both expect OK it gets complicated.

I am on my own at the moment so I'd appreciate some help and inspiration here.

答:
AT commands are generally not designed to be multiplexed over a single channel, so if you have sent multiple requests without waiting for the responses, it is very likely that you will get the responses in the same order as that you sent the requests (although it is better to simply wait for a final response before sending the next request).

If it is possible that you get unsolicited messages intermixed with the request/response messages, you could chain the message handlers.

If you do that, you first present a received message to the response handler of the oldest unfinished request. If that handler indicates it couldn't process the message, you go to the next handler in the chain (the next oldest unfinished request). If you reached the end of the chain of unfinished requests, you present the message to the handler(s) for unsolicited messages.

Once any handler indicates it has processed the message, you stop the chain right there and no further handlers will get to see it. This prevents responses like OK to complete multiple requests.

This can be implemented using the Chain of Responsibility pattern, or simply as a loop over an ordered list of message handlers.


答:
so, to recap:

your shapes have actual names, determined by some outside entity (possibly user input), and aren't always just Circle1 etc.

you don't think the shape should be responsible for this property (namedness? nominativity?)

Well, assuming you don't use a global logger and the logger itself has a sane interface, you can create a named logger proxy: either that's passed to the Shape constructor, or you wrap them both in a NamedShape which passes the proxy to each forwarded method.

Then, every line logged to the proxy is just forwarded to the real logger, with the name prepended.

Title: Store an object's name in the object or externally?

Body:
I'm in the process of building an application which needs extensive logging of points in time at which certain events happen. For example when it renders a sequence of different shapes to the screen then we need a logfile with info like 'shape A rendered to surface at time X, shape B rendered to surface at time Y, surface flipped at time C' etc. in response to comments These names (A,B) should be meaningful and will either be user-defined (e.g. 'MyGroupOfRectangles') or automatically generated (like shape type + number, e.g. 'Rectangle1' or for bitmaps/avis/... use the filename). Main reason for this is that most of the time the logfile is going to be interpreted simply by the user reading it and quickly checking out if the sequence is doing what he/she wants to.

In order to make this happen it's clear that at the moment the log function is invoked it needs to know the name of the shape it's going to log about. One could just give any type of object which is going to be logged about a string member. However thinking about that there are some implementation- and design-wise questions which make me doubt that approach. But other approaches in turn have other problems.

The major question being (almost philosophical - I'm probably overthinking this): should an object know it's own name? After all it's merely an implementation detail here, used solely for logging - if I wouldn't want to log Shapes by their name they wouldn't need to be named at all.

So does it make sense to stuff the name in there as well, or would it be a better practice to keep a map somewhere which links object instances to a name? Something like

```<code>Map< Shape, string > shapeNames;

string NameForShape( Shape s )
{
  return shapeNames.Contains( s ) ? shapeNames[ s ] : "<unnamed>";
}
</code>```

This is very much unintrusive but does introduces some other potential problems in keeping the map up to date with existing shapes: should a shape be destructed, it's name also has to be erased from the map.

The other option (or if there are multiple other options, by all means let me know) is to make a Shape returns it's name. Being an interface it could be like this:

```<code>interface Shape
{
  void Render();
  ...
  string Name();
}
</code>```

However this means every implementation has to take care of providing the Name() implementation and they're likely to going to be doing that all in the same way, like

```<code>class Rect : Shape
{
public:
  Rect( string name ) : { this->name = name; }

  string Name() { return name; }

private:
  string name;
}
</code>```

That's quite some boilerplate and DRY is a holy rule so raises more questions: do I get rid of the pure interface and make it abstract instead (not ideal for unit testing)? Or do I add an extra layer with a default Shape implementation like NamedShape which partially implements Shape and just provides Name() (extra inheritance layer is not ideal either)?


问:
Why do we use non-descriptive internal codenames?
I think using codenames are quite widespread. Our company is using them too.

But my main concern is these names are usually not documented anywhere. And the meaning is spread by the word of mouth. And the names have nothing to do with function of the tool or entity it's named.

I see the pattern that the internal test machines are named after constellations, Public facing servers are named after Greek gods. And projects are named after places or the name of some randomly chosen film star or character name. But no information directly available from the name whether the machines are Windows or Linux; 32 or 64 bit servers. Or what's the project about.

I just have a bad gut feeling when I see the commit message of the VCS that someone just branched the "Gandalf" project or the "Callanish" project or whatever project. Just for the same reason, you generally don't name your functions and variables like that.

I proposed that we should use more descriptive names, at least for the new entities, but I faced very strong opposition. Apparently everyone in the organization except me love naming stuff like that.

So why do we use non-descriptive codenames?

Don't get me wrong I have no problems naming program versions and milestones, or having a nice product name for marketing reasons. But all other places I would better like to see descriptive names.

EDIT:

To give you some context: Gandalf is project that ports the code 64 bit. Callanish is which ports it to Android... I'd rather call the former branch 64bitporting and the latter androidporting. Maybe a suffix attached to it denoting the target version we plan to ship it. So everyone would know by name what it is.

The servers in question are virtual machine images we test the product on... I don't know the physical machine it actually runs on though. So calling them windowsxp_32, windows7_64, debian_32 or solaris_64 is totally fine.

答:
Descriptive naming is hard™, it's much easier if you already have a theme which automatically comes with a list of words you can use.

When you have multiple of the same object naming them foo1.6, foo1.2, etc. quickly gets confusing/prone to mistakes. For example when you need to run your test on Virgo then you will quickly notice the mistake if you are happen to be on Cancer.

It also makes for an entertaining meeting when the naming conventions is rolled out and the decision is made to base the conference room names after music genres and you name the cafeteria Salsa.


答:
We don't reference people by their characteristics as it takes all day to list them in enough detail to be unambiguous and the characteristics can change.  What if they get a haircut?  Instead we give them names.  Also, people are better at remembering words than streams of random symbols.

Disclaimer: This is going to contain some opinion and anecdotal tales due to the question.

In a place I worked a couple of years ago, all our servers were named after moons and body parts. "Rhea","Miranda", "lung", "kidney" etc.

Up high decided, like you, that this was all a bit silly and we should change them to more "descriptive" names like "arc-sql-w-4" or "lon-web-lin-2".  This was met with much opposition. But it went through.  We renamed everything.

So what went wrong?

Previously, we'd know off the top of our heads which machines were the primary databases and which were the slaves because we could remember "heart" controlled "head" or that "Tarvos" was an application server for X.  Whatever.  Now we had to remember an obscure pile of symbols that partially, but not fully described the machine we were looking for.  We had to know via some lookup table in our heads that "lon-web-lin-1" was an application server for product A and "lon-web-lin-2" for product B.

It's similar to the reasons you should use passwords like FartDownTrousersForALivingDoYou? instead of 43gH5#€1.  People are good at remembering words, not random piles of junk.  Words are symbols that refer to things.

Another (arguably more practical) problem is that you're tying your DNS and server names to their functions.  Which means you can't change the function without changing the name.  For us this included physical location and operating system too.  Which is a massive pain in the arse.

Also, and this is the last point.  Names are far more fun.

What about project names?

Well, instead of "Project Gandalf" what do you propose?  "Project prototype function X and see if we can evolve it into a product"?  What if the project scope changes, do we then rename the project?  Again, names are shorthand symbols that refer to things.

Title: Why do we use non-descriptive internal codenames?

Body:
I think using codenames are quite widespread. Our company is using them too.

But my main concern is these names are usually not documented anywhere. And the meaning is spread by the word of mouth. And the names have nothing to do with function of the tool or entity it's named.

I see the pattern that the internal test machines are named after constellations, Public facing servers are named after Greek gods. And projects are named after places or the name of some randomly chosen film star or character name. But no information directly available from the name whether the machines are Windows or Linux; 32 or 64 bit servers. Or what's the project about.

I just have a bad gut feeling when I see the commit message of the VCS that someone just branched the "Gandalf" project or the "Callanish" project or whatever project. Just for the same reason, you generally don't name your functions and variables like that.

I proposed that we should use more descriptive names, at least for the new entities, but I faced very strong opposition. Apparently everyone in the organization except me love naming stuff like that.

So why do we use non-descriptive codenames?

Don't get me wrong I have no problems naming program versions and milestones, or having a nice product name for marketing reasons. But all other places I would better like to see descriptive names.

EDIT:

To give you some context: Gandalf is project that ports the code 64 bit. Callanish is which ports it to Android... I'd rather call the former branch 64bitporting and the latter androidporting. Maybe a suffix attached to it denoting the target version we plan to ship it. So everyone would know by name what it is.

The servers in question are virtual machine images we test the product on... I don't know the physical machine it actually runs on though. So calling them windowsxp_32, windows7_64, debian_32 or solaris_64 is totally fine.


答:
Naming things by their properties is a fundamentally bad idea. The reason is that properties are, by definition, changeable phenomena, while the identity of a thing stays the same even if properties are changed.

Someone decides that the file server should be migrated to Linux? If its name is "Apollo", that's not a problem. If the name referenced "windows", then it would either become misleading, or have to be changed everywhere at great expense or risk. You're introducing a new output format? For the love of God, don't call it 'newFormat'! It will eventually be replaced yet again, and the even newer format will need an even more descriptive name to distinguish it. Either call it '3', so you can later boost it to '4', or 'gold' so you can upgrade to 'platinum'.

(An additional reason is that names composed of nuggets of information are butt-ugly. No one wants to work on a computer named "PC-Marketing-Windows7-143" - they'll take "Apollo" or even "Bacchus" over that any day. But the main point is the identity/property divide.)


答:
There are 3 reasons, in my experience:

When you have to name lots of similar things it can be hard to find unique descriptive names for all of them.  People need a short unique way of referring to it, and we're better at using names than we are at using numbers (unless the number is very short).  When you give it a name, it tends to take on a personality in your mind, so you'll remember that server Gandalf is the one with the flaky power connector better than SERWIN15AB23.  It's also less likely that you'll confuse two of them with a typo.

The naming process can be fun.  Some companies do it with a vote.  Other people enjoy coming up with unique names.  Just ask any parent.

For external projects, it's usually marketing that decides what the name is, and normally they do that right before it ships.  When did Microsoft decide to call the latest OS "Windows 10"?  I doubt it was always called that.  The project might be in development for a long time before that, and in some cases you want to obfuscate it so people outside the company don't know what you're talking about.


答:
The important question is: what is descriptive? The other answers have done a great job illustrating what is not descriptive.

Let's establish that descriptiveness comes from calling things by their role, their purpose. By what they do. For example, it's pretty clear, what a "cutter" does. Now it could be an ax, a laser or a knife. It doesn't matter so much. And a laser could also be a "pointer" an ax can also be a "decorator" and a knife can also be a "puncturer".

So, as others have pointed out, the relationship between the properties of something and the task it fulfills is relatively loose. Therefore OS being part of the server name is not descriptive, it is distracting from the true purpose.

Unless it is your job to work on how component DoesX accomplishes X, it is none of your business. If it is your job, then you are immediately confronted with it anyway.

As rachet freak pointed out, it is sometimes hard to find descriptive names. But more often than not, that is a sign of not having understood what the things do, that you must name. Before having that understanding, you probably shouldn't concern yourself with how it does that which you don't know ;)


问:
What causes overtime and how can it be avoided?
Today, my manager told me that I must work over time to make up for a lack of planning and project management. Instead of incentivizing this unpaid mandatory overtime, my manager has made it clear I have no choice in the matter.

This isn't a single project. We currently have a dozen projects all on the go at one time, and I simply can't get them all done. Therefore, I must work overtime so we don't have to push deadlines.

Is this a sign of an ignorant or disrespectful manager, or simply an inexperienced one?

I'm in this position because of a lack of planning and project management (I think). How might I avoid this in the future? I'm no Project Manager, it isn't my strength.

What are good ways to get an employee to work overtime if you can't directly pay them? Good incentives, etc.

From what I hear, gaining your employee's respect is the single best way to get your employees to work over time, although you should never make a habit of it.

答:
Work at a pace you can keep up until the end.  Sacrificing your health not only is bad for you, but it is actually bad for the company, too.  The goal is to climb the whole mountain, not break your ankle sprinting the first 1,000 meters.

You have to acknowledge reality.  At some point you might have to be willing to say "no": the world will not stop spinning if the project fails...


答:
there may well be a system you just don't know.

One company I worked for used names of Nobel prize winners for all their servers. Different Nobel prizes indicated different categories of servers.

Test servers might be named after mathematics winners, database servers after literature winners, mail servers after medicine winners, etc. etc.

To someone not familiar with the naming convention, the names seemed completely random (especially as most people don't know all those hundreds of Nobel prize winners over the decades).

I've used a similar system at home, naming computers after jet fighters, servers after bombers, and disk volumes after volcanoes.

Same could be done with pieces of software, name production versions after trees, beta versions after flowers, etc. etc.


问:
using one database connection across multiple functions in python
whats the best way to go about this in python? I have a number of like so

```<code>def test1()
    .... code .....
def test2()
    .... code .....
def test3()
    .... code .....
</code>```

how could I create one database connection and use it across all the functions? I'm connecting to my database in a test file like so:

```<code>import MySQLdb as mdb
import sys

try:
    con = mdb.connect('10.243.17.13', 'mark', '********', 'dex');

    cur = con.cursor()
    cur.execute("SELECT VERSION()")

    ver = cur.fetchone()

    print "Database version : %s " % ver

except mdb.Error, e:

    print "Error %d: %s" % (e.args[0],e.args[1])
    sys.exit(1)
</code>```

答:
The best thing it occurs to me it's creating a class, so you can save the connection in an attribute, and then use it by all the test methods. In example:

```<code>import sys
import MySQLdb as mdb

class MyDBTest():

    def __init__(self, host, user, passw, db):
        try:
            self.con = mdb.connect(host, user, passw, db)
            self.cur = self.con.cursor()
        except mdb.Error, e:
            print "Error %d: %s" % (e.args[0], e.args[1])
            sys.exit(1)

    def show_version(self):
            self.cur.execute("SELECT VERSION()")
            print "Database version : %s " % self.cur.fetchone()

    def test1(self):
        # Do something with self.con or self.cur
        pass

    def test2(self):
        # Do something with self.con or self.cur
        pass

if __name__ == '__main__':  # If it's executed like a script (not imported)
    db = MyDBTest('10.243.17.13', 'mark', 'LiverpoolFc', 'dex')
    db.show_version()
    db.test1()
    db.test2()
</code>```

In the example I've put the error checking (try-except) inside the class. But you could also don't put it in there and leave the main (__name__ == __main__ part) to handle the errors if they occurr inside MyDBTest.

ContentLicense: CC BY-SA 4.0

Body:
The best thing it occurs to me it's creating a class, so you can save the connection in an attribute, and then use it by all the test methods. In example:

import sys
import MySQLdb as mdb

class MyDBTest():

    def __init__(self, host, user, passw, db):
        try:
            self.con = mdb.connect(host, user, passw, db)
            self.cur = self.con.cursor()
        except mdb.Error, e:
            print "Error %d: %s" % (e.args[0], e.args[1])
            sys.exit(1)

    def show_version(self):
            self.cur.execute("SELECT VERSION()")
            print "Database version : %s " % self.cur.fetchone()

    def test1(self):
        # Do something with self.con or self.cur
        pass

    def test2(self):
        # Do something with self.con or self.cur
        pass

if __name__ == '__main__':  # If it's executed like a script (not imported)
    db = MyDBTest('10.243.17.13', 'mark', 'LiverpoolFc', 'dex')
    db.show_version()
    db.test1()
    db.test2()

In the example I've put the error checking (try-except) inside the class. But you could also don't put it in there and leave the main (__name__ == __main__ part) to handle the errors if they occurr inside MyDBTest.


答:
One reason for codenames is obfuscation.  If you make the name of a project meaningless, then you can talk about it in public without anyone else understanding what you are discussing.

Similarly, if you give your servers meaningless names, then nobody except the authorised users will have any idea what's on them.


问:
Why use Creational patterns in Java?
How are Creational patterns useful? Most of the material I came across explains the use case to "solve common problems associated with object creation, improve flexibility".

I can think of just two similar cases where these might help:

Encapsulating object creation code into a factory like class, so that all object creation code is in one place, and any modifications would require changes only in one place.

Making object creation dynamic, whereby the required concrete type can be returned based on some parameters.

I am not able to exactly understand what problems creational patterns solve. What unfavourable consequences could one face by not using creational patterns?

It would be great if some one could elaborate on this with real code examples.

答:
The Singleton is classified as a creational pattern, so that's one obvious use: ensuring that everybody always communicates with the same instance. (The benefits of this are controversial, but I didn't say it was a good use. Just a rather obvious use.)

Factory methods spare an API user from knowing (and maintaining over time) overly specific helper class names. When you order pizza, you don't care whether a MotorizedBicyclePizzaCourier, a WalkingPizzaCourier or a TeleportPizzaCourier serves you - you only need to know that you're dealing with a PizzaCourier. This leaves the pizza place free to introduce new delivery methods without requiring their customers to upgrade anything.

Builders allow you to simplify the low-level syntactical details of creating objects. That's not as world-shakingly important as some other things (which affect correctness or maintainability), but it's not nothing, and often a good idea for objects with many attributes.

That's not all, but I hope you get the idea: different creation patterns have different (although similar) uses and advantages. They are lumped into one category mainly because there are now too many design patterns to treat them all as one huge list.

Title: Why use Creational patterns in Java?


问:
Linking against LGPL - How to share the code?
I'm working on an Open Source software project (LGPL) which uses another LGPL-licensed software. To make it easier for users and developers I'm delivering and linking against the compiled thirdparty.

As far as I know I have to include the sources and license-statements of LGPL software if I'm delivering and using it in binary form.

However this would mean that I have to put the compiled version as well as the code of that thirdparty into my repository. Not only would that make the checkout take ages, it would also be somewhat redundant.

Are there any techniques or best practices on how to solve this issue? My project is available on Github  if that matters.

Update:

Link to Project

Link to Thirdparty

答:
The GNU FAQ says the following, which should pretty much answer your question:

Can I make binaries available on a network server, but send sources
  only to people who order them?

If you make object code available on a network server, you have to provide the Corresponding Source on a network server as well. The
  easiest way to do this would be to publish them on the same server,
  but if you'd like, you can alternatively provide instructions for
  getting the source from another server, or even a version control
  system. No matter what you do, the source should be just as easy to
  access as the object code, though. This is all specified in section
  6(d) of GPLv3.

The sources you provide must correspond exactly to the binaries. In particular, you must make sure they are for the same version of the
  program—not an older version and not a newer version.

So, e.g. just put a link into an About-dialog of your program which should point to a server under your control or a versioning system like git (and probably github).

Be careful about what the other answer suggests:

just give a contact email for the source and auto reply with a link where you got the library from originally if you didn't modify it or a link to a zip in a dropbox with the modifications.

This is basically the opposite from what the GNU-FAQ says. It seems like you are not allowed to only provide the source code on request (maybe if you only distribute your binaries on request but certainly not if you provide them on a webpage). Most likely you will never get in trouble if you do what ratchet freak suggests, but that doesn't mean that it is the right way.

A linked entry about version control systems the the FAQ-section cited above, says:

Users should be provided with clear and convenient instructions for how to get the source for the exact object code they downloaded—they may not necessarily want the latest development code, after all.

So make sure you comply with this by, for example, specifying the program's current version number in the About-dialog and setting concurrent tags in the git repository.

And at the end the obligatory "I am not a lawyer" note ;)


问:
Order by different Enum property each row
So I have a list of DefaultSearchModal items that have an enum called TypeSearch in every list item. I would like to order the list to have a different enum property each row.

So if you have an unordered list by this:

1,1,2,2,3,3,4,4,5,5,5,5,5,5

I would like to order it to:

1,2,3,4,5,1,2,3,4,5,5,5,5,5

What would be a good algorithm to sort it like this?

```<code>    public class DefaultSearchModel
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string Url { get; set; }
    public TypeSearch TypeSearch { get; set; }
}

public enum TypeSearch
        {
           News = 0,
           Blog = 1,
           Photo = 3,
           Page = 4
        }
</code>```

答:
Go once through the list and divide them up in 5 sets.

Then simply take one object (if available) from each set in order, and put them into
your output list

Repeat step 2 until all sets are empty

Algorithm has O(n)


问:
Should I throw std::bad_alloc?
I am allocating memory on the stack, and distributing it manually to shared pointers. I end up doing something like this at startup (I've simplified it by ignoring alignment issues):

```<code>char pool[100];

std::shared_ptr<Obj> p = new(reinterpret_cast<void*>(pool)) Obj;
pool += sizeof(pool);
</code>```

Of course, it is possible that the 100 is not enough, so in that case I'd like to throw an exception:

```<code>char pool[100];
char* poolLimit = pool + 100;

if (pool + sizeof(Obj) >= poolLimit)
  throw std::bad_alloc(); // is this a good idea?

std::shared_ptr<Obj> p = new(reinterpret_cast<void*>(pool)) Obj;
pool += sizeof(pool);
</code>```

Is it correct to throw a std::bad_alloc here? Or should I just throw std::runtime_error?

答:
(I'm assuming you are writing an user-mode application here, not a kernel module, device driver or network stack).

Throw std::bad_alloc. Only an idiot would try to catch that.

But it doesn't really matter what you throw because the application is dead at that point anyway. What you want is for the application to quit at that point in a clear and unambiguous way. Calling abort would be even better.

If you are operating out of a fixed buffer you really need to make sure it is big enough for all needs.

Title: Should I throw std::bad_alloc?


问:
What do you put into an Architecture Specification?
I'm currently revising a number of document templates for my company. One thing we've never had is a formal Architecture Specification, so I'm starting to put one together. </p>

<p>What sort of things do you put into your architecture specs? Feel free to copy and paste a table of contents - that would be helpful. Are there any good templates already available on the web? </p>

答:
How often do you see your architecture changing? Will your team religiously update the document with each refactor/new feature? Will the document last the lifetime of the project? How big is your team? Who is the audience? To what detail do you want to document?

In my experience, a team's formal architectural documents tend to fall by the wayside very quickly. When everyone on the team knows each other and the team is small, I tend to avoid these documents. They get out of date and lead new developers astray. Documents are eeevil. A solid team that openly communicates with each other trumps formal architecture docs any day.

At some point such person-to-person communication cannot scale. You must now correctly chose the level of <s>eeevil</s> documentation that applies to the size and scope of your project. Remember too much formality will mean changing the documents becomes too cumbersome. So much detail may be documented that maintaining the documents becomes onerous. You get out of date docs that stay out of date too long. Too little formality means that the team in Seatle has no idea what's going on.

Medium sized teams could do well with just a wiki. Very large teams may wish to have full-time documentation staff that assist in maintaining extremely formal documentation.  At this point, documentation should be more than a convenience and the team should make it mandatory.


问:
Do I need to include a copy of the GPL / LGPL to every copy of my program?
Is it necessary to include the GPL / LGPL license text to every distributed copy of my program? Or can I just put a link in the About-dialog?

答:
TL;DR

Yes, because the link might become invalid in 5 or 10 years.

Detailed Version

Yes, this is necessary. You cannot just include a link pointing to the license text. The reason is clearly stated in the GNU FAQ:

Why does the GPL require including a copy of the GPL with every copy
of the program?

Including a copy of the license with the work is vital so that everyone who gets a copy of the program can know what his rights are.

It might be tempting to include a URL that refers to the license, instead of the license itself. But you cannot be sure that the URL
will still be valid, five years or ten years from now. Twenty years
from now, URLs as we know them today may no longer exist.

The only way to make sure that people who have copies of the program will continue to be able to see the license, despite all the
changes that will happen in the network, is to include a copy of the
license in the program.


问:
How to detect subtle changes in a website?
My friend and I were discussing a script for automating a certain task and the solution involved using Selenium to automate the pressing of certain buttons.

However when we click the send button of a form, how do we know it always has the same function?  Even if a script works the first 100 times, the page may totally change 101.

In our case, I would like to open my e-mail account and automatically respond to some messages.  However it is possible the buttons can move around.

Therefore our automation task will break whenever the website changes and we can't do anything except build from scratch and identify the change however small it is.

Is there any way to build robust automation tasks?

Programmatically, it seems impossible to detect changes in JavaScript since these scripts can be thousands of lines long.

答:
In general, that's why for everything involving automation, you don't interact with a web application through web interface, but, in general, through an API.

If you try to access your own web application, create an API. Instead of Selenium, your automation task would be to simply make an API call with curl or similar tools.

If you try to access a third-party web application, there are chances you're not only doing it wrong, but also doing something which is prohibited by the owner of the concerned website. Unless you have a lawyer in your company, you consulted him, he explained you the risks of doing what you're doing and you understand and accept the risk, contact the owner asking for an API.

In your specific case, since your automated task involves accessing e-mails, you may want to search for those three keywords: POP3, IMAP and SMTP. Web interfaces should be irrelevant in your case.

Or maybe you don't even need to write a single line of code. Many e-mail clients contain filtering, as well as auto-response features; by combining both, you may find that the solution to your problem is just a clicks away (with a huge benefit of having exactly 0 LOC to maintain over the years).

Note: the fact that a button moves on a page shouldn't bother Selenium, since you're expected to access them through selectors, not by absolute position anyway.


答:
This may be related to high context or low context culture. Every company, organization, or team has its own culture. High or low context culture means how much information a culture likes to relate explicitly, and how much people are expected to take from context.

Naming all the services with names from cultural references does provide some flexibility, but also lacks explicitness. There has to be word of mouth or "tribal knowledge" that supplements the names -- i.e. the context of the service. I have seen situations where for example there's the "fizzbuzz" server, or the "marcopolo" service that no one knows what they do, but they get traffic, so they must do something.

I'm a low context person, so I tend to choose simple, explicit names that provide context about the purpose a server or service. I also write "self-documenting code" where I'm careful about naming in my code to make it more readable.

But I'm currently working in a high-context shop where all the services are named after Transfomers. Sigh. At least they use the names consistently.

So it seems more like a cultural value, but technical practices will adapt to the cultural preferences.

High-context can also be funnier, and there is some value in that.


问:
Designing a system to archive databases with referential integrity
I have a very large Oracle database, with many many tables and millions of rows. I need to delete some of the rows end-to-end. By end-to-end, I mean, if I want to delete a row from a table then I must delete all the corresponding records in child tables first and ensure that deletion happens without any constraint violation errors while deleting the parent table entry.

As an example:

```<code>Table A defines dependency over Table B and Table C (means Table A has foreign key constraint on Table B and Table C).
Table B defines dependency over Table C and Table D.
</code>```

I want do delete rows in this specific order something like this:

Table A<=Table B<=Table C<=Table D

I have come up with two approaches:

Using a service API which takes parent table rowID and archives whole data in JSON format and keeps on deleting the entry using cascade option.

Other option is to use delete-with-cascade along with triggers to save the deleted values.

Once data is fetched, I want to better put it in similar archived tables Table_A_archived, Table_B_archived etc or If it could be fetched in file, that is fine too.

Any thoughts on initial approaches will be really valuable. If anyone has done this sort of thing before, it will be great to learn from their experience.

Just FYI, this is a live database and I can't do absurd things (I can obviously test it before pushing it to prod :)). Also, deletion/archival is not just on the basis of time.

Thanks in advance!

答:
Moving the data to archive tables will reduce the amount of data in the "live tables", but it won't reduce your overall database size. So if that is your goal, use files, which can be compressed easily if necessary.

However, if you want to be able to query your archive data later on, and database size is not really your problem, the archive tables may be the better choice.

The usage of triggers makes IMHO only sense if your archiving process has to happen synchronously during your production process (for example, whenever a DELETE command is issued to your data in the normal production, you want immediately the related records to be archived). On the other hand, if your archiving process is designed to be an asynchronous process, maybe executed at after-work hours, with a time-stamp filter for identifying the data to be archived, there is no need to use triggers. Instead, you can design your archive process using some bulk deletes, which can be significantly faster than deleting one record after another.


答:
Why use creational patterns (in Java)?

The main reason for creational patterns is to separate the creation of an instance from its consumption.

That seems in the first place rather abstract, but has easy to see consequences.

1) You hide creational logic from the consument of an object-instance. As a consument you are not interested in how an instance is created. You only have a concrete demand (Service, Repository, etc.). Each demand is a dependency of your object. Which leads to

2) You are able to insert dependencies from the outside, aka dependency injection.
If you are able to inject/substitute dependencies of an object, you are better able to write unit-tests. Say you need the result of a complex DB-query or the result of several web-service-calls; you could easily inject those results from the outside or stub results.
Furthermore you could mock / stub out the creational objects itself, which could be used to deliver other mocks / stubs.

Better / more testable code leads to higher code coverage, which leads in the best case to better / higher code quality.

You could do your dependency injection by hand or use some kind of automation, e.g. Spring-framework or the like.

What unfavourable consequences could one face by not using creational patterns?

The downside of not using creational patterns should be clear from what was said above: It makes your code harder to understand and test.

real code examples:

Suppose you have a car, which itself has an engine. A typical way to implment it is this

```<code>public class Car {

    Engine engine;

    public void start(){
        engine.start();
    }

    public void stop(){
        engine.stop();
    }

    public Car(){
        engine=new Engine();
    }
}

public class Engine {

    public void start(){

    }

    public void stop(){

    }

}
</code>```

You have a car, which instantiates its engine. Via the interface of the car, you are able to start/stop the car/engine.

This is bad in many ways:

1) you are not able to change the engine, the car runs with. That might not seem bad, since you intended the car to run only with the given engine

2) but, you could not swap the real engine_ out for a testengine.

You have to take two steps to improve the design:

1) separate the consumption of the engine from its use
2) use a factory pattern to encapsulate the creation of the engine

The improved car:

```<code>public class Car {

    Engine engine;

    public void start(){
        engine.start();
    }

    public void stop(){
        engine.stop();
    }

    public Car(Engine engine){
        this.engine=engine;
    }
}
</code>```

The advantages are:

ability to swap the engine for the car

ability to swap the factory for the engine

So the whole creation of the car could be abstracted away with a builder:

```<code>public class CarBuilder {

    EngineFactory engineFactory;

    public Car build(){
        return new Car(engineFactory.produceEngine());
    }

    public CarBuilder(EngineFactory engineFactory){
        this.engineFactory=engineFactory;
    }

}
</code>```

Which itself could be mocked/stubbed.

Title: Why use Creational patterns in Java?

Body:
How are Creational patterns useful? Most of the material I came across explains the use case to "solve common problems associated with object creation, improve flexibility".

I can think of just two similar cases where these might help:

Encapsulating object creation code into a factory like class, so that all object creation code is in one place, and any modifications would require changes only in one place.

Making object creation dynamic, whereby the required concrete type can be returned based on some parameters.

I am not able to exactly understand what problems creational patterns solve. What unfavourable consequences could one face by not using creational patterns?

It would be great if some one could elaborate on this with real code examples.

Body:
Why use creational patterns (in Java)?

The main reason for creational patterns is to separate the creation of an instance from its consumption.

That seems in the first place rather abstract, but has easy to see consequences.

1) You hide creational logic from the consument of an object-instance. As a consument you are not interested in how an instance is created. You only have a concrete demand (Service, Repository, etc.). Each demand is a dependency of your object. Which leads to

2) You are able to insert dependencies from the outside, aka dependency injection.
If you are able to inject/substitute dependencies of an object, you are better able to write unit-tests. Say you need the result of a complex DB-query or the result of several web-service-calls; you could easily inject those results from the outside or stub results.
Furthermore you could mock / stub out the creational objects itself, which could be used to deliver other mocks / stubs.

Better / more testable code leads to higher code coverage, which leads in the best case to better / higher code quality.

You could do your dependency injection by hand or use some kind of automation, e.g. Spring-framework or the like.

What unfavourable consequences could one face by not using creational patterns?

The downside of not using creational patterns should be clear from what was said above: It makes your code harder to understand and test.

real code examples:

Suppose you have a car, which itself has an engine. A typical way to implment it is this

public class Car {

    Engine engine;

    public void start(){
        engine.start();
    }

    public void stop(){
        engine.stop();
    }

    public Car(){
        engine=new Engine();
    }
}

public class Engine {

    public void start(){

    }

    public void stop(){

    }

}

You have a car, which instantiates its engine. Via the interface of the car, you are able to start/stop the car/engine.

This is bad in many ways:

1) you are not able to change the engine, the car runs with. That might not seem bad, since you intended the car to run only with the given engine

2) but, you could not swap the real engine_ out for a testengine.

You have to take two steps to improve the design:

1) separate the consumption of the engine from its use
2) use a factory pattern to encapsulate the creation of the engine

The improved car:

public class Car {

    Engine engine;

    public void start(){
        engine.start();
    }

    public void stop(){
        engine.stop();
    }

    public Car(Engine engine){
        this.engine=engine;
    }
}

The advantages are:

ability to swap the engine for the car

ability to swap the factory for the engine

So the whole creation of the car could be abstracted away with a builder:

public class CarBuilder {

    EngineFactory engineFactory;

    public Car build(){
        return new Car(engineFactory.produceEngine());
    }

    public CarBuilder(EngineFactory engineFactory){
        this.engineFactory=engineFactory;
    }

}

Which itself could be mocked/stubbed.


问:
Why don't replace HTML with JSON as base web design technology?
Since JSON shows a lot of benefits over HTML, why don't just abandon HTML?
Qt frameworks with QML shows it is perfectly possible to use JSON to design rich content

EDIT:

Many of you think about this question in terms of performance vs html but i'm not about that.

HTML is just less readable and it's not enough per-se to describe UI behavior, look and feel. Maybe a technology shift is needed. I think from the developer point of view.

What about a browser capable of rendering a QML like web-page for example? QT with QML uses google V8 engine to do its work.

If you can write a web page in a technology that is not HTML, people will start using it.
Browser could support HTML for a long time and allow developers to code with less stress

答:
While JSON has a benefit in terms of size (and so bandwidth) and simplicity (slightly easier to parse for smartphones), such major change of replacing one language by another would be too disruptive to justify the minor gains in bandwidth and performance. Such gains were maybe relevant ten years ago where mobile devices were very limited in terms of CPU and when many people had only access to low-speed internet, but today, it's much less relevant.

If you're not convinced, take an ordinary e-commerce website, measure the time spent:

Downloading and parsing (sometimes minified and usually gzipped and cached on client side) HTML.

and compare it to the time it takes to:

Download minified JavaScript source,

Download images,

Download CSS,

Parse CSS,

Render the page,

Execute JavaScript.

Now, if you identified that after minifying HTML, gziping it and adding client-side caching, the loading and the parsing of HTML is still the bottleneck on your website, nothing forbids you, using current standards, to make a fully AJAX website, sending practically only JSON to your users.


答:
You are assuming JSON is always better than HTML, which is controversial at best (see MainMa's answer). But let's assume you're right. Why don't we get rid of HTML?

The surface answer is compatibility, but why is compatibility even an issue? The fundamental reason you can't make these kinds of changes on the web is because the web is a decentralized system built on communication protocols. So even if a majority of the web switched to JSON tomorrow, any cohort of the web still using HTML could function. There is no central switch.

Title: Why don't replace HTML with JSON as base web design technology?

Body:
Since JSON shows a lot of benefits over HTML, why don't just abandon HTML?
Qt frameworks with QML shows it is perfectly possible to use JSON to design rich content

EDIT:

Many of you think about this question in terms of performance vs html but i'm not about that.

HTML is just less readable and it's not enough per-se to describe UI behavior, look and feel. Maybe a technology shift is needed. I think from the developer point of view.

What about a browser capable of rendering a QML like web-page for example? QT with QML uses google V8 engine to do its work.

If you can write a web page in a technology that is not HTML, people will start using it.
Browser could support HTML for a long time and allow developers to code with less stress


问:
What are the skills you look for when hiring a fresher/newbie for developement?
I really want to ask this questions to my fellow developers here in Programmers.SE because i am hiring freshers for my company.. Even though i know some basic questions that can be asked to a fresher during interview and i want to know,

What are the skills you look for when hiring a fresher/newbie for developement?

答:
I mostly check for basic programming skills and look for good aptitude. For Aptitude you can ask them to solve them some basic mathematical problems.

I strongly believe that a only good maths guy can be good programmer. If someone's maths is weak he cannot ever ship good code or write good algorithms.

Freshers with these basic qualities can be trained and made productive in no time.


答:
Because the change would bring more pain than benefit.

Let's assume that you are right and that JSON is better than HTML for the job of defining web pages. Well, okay, but that's not enough to justify the change. There would have to be tangible benefit.  Maybe raw web pages would be easier to maintain and quicker to download -- but we mostly don't edit raw HTML anymore, and download time is mostly about server load and media size.

On the other hand, the cost of change would be horrific.

Sorry to be cynical, but there (IMO) you go.


答:
The first reason is that it can be short and memorable. If you think about how many times you are going to say or write the name of the project, you save a substantial amount of time if there is a brief name that everyone knows and understands.

The second reason is that it builds camaraderie. If the team gets to pick the name, that can pick one that they all like. It is subtle, but it boosts team morale when you are working on a project named Viper or Gimley or Boba or Bugatti instead of a project named 'Q3 Accounting Updates'. I had a friend who worked on a team with a bunch of car enthusiasts. Their favorite project kickoff ritual was picking which car they would use as the project code name.


答:
I've always thought this is something that's done mostly because it amuses people. People are conditioned by the media to attach value to skulking around in the dark vs. operating in the light of day. At age 5 we have "Special Agent Oso"; at age 15 it's James Bond. Secrecy lends an air of importance to people's otherwise mundane activities (e.g. programming a computer).

Relatedly, someone made a logo for "Longhorn" back when that was a Microsoft codename (http://en.wikipedia.org/wiki/File:Windows_Longhorn_logo.svg). Why would someone make a logo for a codename that's not intended to ever really be a part of any marketing effort? Again, people do this sort of thing because it amuses them. Playing around in Photoshop is easier / more fun than actually doing real work.


问:
Does scrum have any merit in defense contracting?
Overheard at the watercooler yesterday: "Scrum has no place in defense contracting."

I tend to disagree in the sense that I believe Scrum can be tailored to work in many scenarios and I can see defense being one of them.  This sparked a huge debate amongst my colleagues (many of us work in defense contracting) with a fairly even split for/against.

To make this a proper question:  Has anyone successfully used (or has experience working with) scrum in a defense contracting situation?  What worked well, what didn't work well and what (if any) modifications to vanilla scrum did you do?

答:
While it may be difficult to fully implement Scrum, it can be beneficial to adopt some of the Scrum practices. For example, now matter how you are doing requirements gathering, you can still have frequent releases and demos. You can still benefit from periodic retrospectives. Look at other processes like Lean or Kanban and see if there is anything they have that can help your team as well.

Instead of dogmatically following any one process, think about how you can improve the process specifically for your team, your project, and in your industry. Process matters. A team's methodology has a major impact on the software that is delivered.


问:
Which package should unrelated classes belong to in Java?
In a project, certain related classes can be grouped together in one package. But some other useful classes are not related to any other class and so cannot be put into a package with any other classes.

A StackOverflow answer I read says that it isn't a bad practice to put such classes in their own packages (just one class in a package), but somehow I feel this is not the best way to go.

So in such situations, what should be done with these unrelated classes?

答:
Typically they should go in a util or misc package. But for example if you have a class DatabaseUtil it can go directly under db, supposing there you also have subpackages db.model, db.dao etc. for other database related classes.

I don't find it at all suitable to have these classes each in its own package (that's not what packages are designed for).


问:
Why is cleverness considered harmful in programming by some people?
I've noticed a lot of questions lately relating to different abstraction techniques, and answers saying basically that the techniques in question are "too clever." I would think that part of our jobs as programmers is to determine the best solutions to the problems we are given to solve, and cleverness is helpful in doing that.

So my question is: are the people who think certain abstraction techniques are too clever opposed to cleverness per se, or is there some other reason for the objection?

EDIT: This parser combinator is an example of what I would consider to be clever code. I downloaded this and looked it over for about half an hour. Then I stepped through the macro expansion on paper and saw the light. Now that I understand it, it seems much more elegant than the Haskell parser combinator.

答:
Because what looks like cleverness to a developer in a burst of creativity can simply pass as mess and just be an unreadable, unmaintainable block of obscure riddles for others.

Still, a nice, clever, well-performing block of riddles, but if you have the experience, you'll often realize that it will cost your business (not you, the developer) at lot more to maintain that thing on the medium- or long-term. So you prefer to calm the ardor of your fellow developers when they get carried.

Except, of course, if there's a justification for the cleverness. And if there's a good documentation that comes along with the obfuscated thing you just wrote. You did comment that clever piece of code, right? Explain it's intent, why it needs to be like, and how it behaves?

If there's no justification, then it's probably just either premature optimization, over-engineering, or a YAGNI kind of problem. If it takes 15 levels of indirection to do something simple, then there's a good chance you fall under of the previous categories as well. And if it's not documented, then it's just trouble.

Great code shouldn't require the maintainer to be at 100% all the time to understand it.
Good code is clever. Great code can be almost as efficient, but better in many other aspects. Great code shouldn't require an IDE with 15 views to follow your application's design.

Note: hey, I've written a few stuff I thought to be clever but that drew WTF? out of - if not my co-developers' - my manager's mouth. Have to look at it from their perspective.


问:
How the Stream.filter() method works?
I know how the lambda expresion works and I know it is an argument for .filter() that establish the criteria to filter with. But I don't get  how .filter() uses the argument, in this case a lambda expression, because .filter() does't have an implementation or at least require one at compile time. I search for this unknown implementation in the Oracle's site but there are just a few words explaning how it works and no code at all.

Is that implemetation hidden or is created automatically by the java compiler?

Does an aggregate operation need one?

double average = roster
  .stream()
  .filter(p -> p.getGender() == Person.Sex.MALE)
  .mapToInt(Person::getAge)
  .average()
  .getAsDouble();
```

roster is a List<Person> instance of ArrayList<Person>

Person is a simple class that represents a person

答:
The Collection interface now has a default method that implements the stream() method that returns the stream. Default methods are new to Java 8 and allow for interfaces to implement methods in order to evolve the API. So this implementation of the stream() method on the Collection must be constructing an object that implements the Stream interface and returns it.

Internally, the Collection interface method stream() forwards a call to the StreamSupport class that is documented. The SteamSupport class in turn constructs an undocumented class called ReferencePipeline that you can find in the java source code in the java 8 JDK.

So, apparently it is the intention of the API designer that if you want to do some custom stream stuff you would go no further than the StreamSupport class.

Title: How the Stream.filter() method works?


答:
Hiring someone fresh out of school is a mixed bag: university is so different than production coding, that unless the potential hire has a long record of open source contribution to show off, there's no telling if he or she will adapt to the real world, let alone how.

The up side is that one gets to introduce that newbie to real-world coding and (hopefully) mold him or her into a useful sort of coder.  That is what I have in mind when evaluating this type of candidate.  I look for one who:

has pursued opportunities to better his/her craft outside of school requirements, whether in the form of open source contributions (preferable) or personal hobby coding

has a logical way of approaching problems

groks hacker culture (or, for bosses other than me, the particular corporate culture the person is being hired in)

is not just intelligent, but also engaged

responds well to correction/criticism and generally isn't someone who's ego I need to protect

knows how to learn on the fly, and learn independently

Body:
I really want to ask this questions to my fellow developers here in Programmers.SE because i am hiring freshers for my company.. Even though i know some basic questions that can be asked to a fresher during interview and i want to know,

What are the skills you look for when hiring a fresher/newbie for developement?


问:
Python multiple inheritance or decorators for composable behaviours
I recently discovered (or rather realised how to use) Python's multiple inheritance, and am afraid I'm now using it in cases where it's not a good fit. I want to have some starting data source (NewsCacheDB,TwitterStream) that gets transformed in various ways (Vectorize,SelectKBest,SelectPercentile).

I found myself writing the following sort of code (Example 1) (the actual code is a bit more complex but the idea is the same). The point being that for ExperimentA and ExperimentB I can define exactly what self.data is, by just relying on class inheritance. Is this really a useful way of achieving the desired behaviour?

I could also use decorators (Example 2). Using the decorators would be less code.

Which approach is preferable? I'm not looking for arguments of the "I like writing decorators better" kind, but rather arguments about

readability

maintainability

testability

pythonicity (yes it's a word).

EXAMPLE 1

```<code>class NewsCacheDB(object):
    """Play back cached news articles from a database"""
    def __init__(self):
        super(NewsArticleCache, self).__init__()

    @property
    def data(self):
        # setup access to data base
        while db.isalive():
            yield db.next() # slight simplification here

class TwitterCacheDB(object):
    """Play back cached tweets from a database"""
    def __init__(self):
        super(TwitterCache, self).__init__()

    @property
    def data(self):
        # setup access to data base
        while db.isalive():
            yield db.next() # slight simplification here

class TwitterStream(object):
    def __init__(self):
        super(TwitterStream, self).__init__()

    @property
    def data(self):
        # setup access to live twitter stream
        while stream.isalive():
            yield stream.next()

class Vectorize(object):
    """Turn raw data into numpy vectors"""
    def __init__(self):
        super(Vectorize, self).__init__()

    @property
    def data(self):
        for item in super(Vectorize, self).data:
            transformed = vectorize(item) # slight simplification here
            yield transformed

class SelectKBest(object):
    """Select K best features based on some metric"""
    def __init__(self):
        super(SelectKBest, self).__init__()

    @property
    def data(self):
        for item in super(SelectKBest, self).data:
            transformed = select_kbest(item)  # slight simplification here
            yield transformed

class SelectPercentile(object):
    """Select the top X percentile features based on some metric"""
    def __init__(self):
        super(SelectPercentile, self).__init__()

    @property
    def data(self):
        for item in super(SelectPercentile, self).data:
            transformed = select_kbest(item)  # slight simplification here
            yield transformed

class ExperimentA(SelectKBest, Vectorize, TwitterCacheDB):
    # lots of control code goes here

class ExperimentB(SelectKBest, Vectorize, NewsCacheDB):
    # lots of control code goes here

class ExperimentC(SelectPercentile, Vectorize, NewsCacheDB):
    # lots of control code goes here
</code>```

EXAMPLE 2

```<code>def multiply(fn):
    def wrapped(self):
        return fn(self) * 2
    return wrapped

def twitter_cacheDB(fn):
    def wrapped(self):
        user, pass = fn(self)
        # setup access to data base
        while db.isalive():
            yield db.next() # slight simplification here
    return wrapped

def twitter_live(fn):
    def wrapped(self):
        user, pass = fn(self)
        # setup access to data base
        while stream.isalive():
            yield stream.next() # slight simplification here
    return wrapped

def news_cacheDB(fn):
    def wrapped(self):
        user, pass = fn(self)
        # setup access to data base
        while db.isalive():
            yield db.next() # slight simplification here
    return wrapped

def vectorize(fn):
    def wrapped(self):
        for item in fn():
            transformed = do_vectorize(item)  # slight simplification here
            yield transformed
    yield wrapped

def select_kbest(fn):
    def wrapped(self):
        for item in fn():
            transformed = do_selection(item)  # slight simplification here
            yield transformed
    yield wrapped

class ExperimentA():
    @property
    @select_kbest
    @vectorize
    @twitter_cacheDB
    def a(self):
        return 'me','123' # return user and pass to connect to DB

class ExperimentB():
    @property
    @select_kbest
    @vectorize
    @news_cacheDB
    def a(self):
        return 'me','123' # return user and pass to connect to DB
</code>```

答:
In general, inheritance is overused. Remember: inheritance is all about the "is a" relationship; modeling hierarchical relationships. Therefore, ask yourself, "Is an ExperimentA a SelectKBest?". That question is nonsensical. SelectKBest doesn't even name a thing; it's an imperative phrase (or the jamming together of one). But let's just say you changed the name to something like TopSelector. Then, the question becomes "Is an ExperimentA a TopSelector?". Again, that doesn't make sense (to me). Without knowing more about your app, it very much seems to be a categorical error. These types have nothing to do with each other. Therefore, inheritance is the wrong thing to use.

This does not mean that decorators are right either though.

Not really sure what decorator best practices are. I'd be wary of stacking lots of decorators. I suppose if they do things that are totally independent, then it's ok. E.g.

```<code>__all__ = []

def export(f):
   __all__.append(f.func_name)
   return f

def author(name):
    def decorate(f):
        f.author = name
        return f
    return decorate

@author('allyourcode')
@export
def SaveTheWorld():
    # Left as an exercise to the reader.
</code>```

One thing that tells us that export and author are independent is that you can apply them in any order, and the result is the same: 'SaveTheWorld' is appended to __all__ and SaveTheWorld.author == 'allyourcode'.

I seem to recall hearing that Guido likes this rule: if decorators stop working when you apply them in a different order, then it's bad.

In EXAMPLE2, order is very significant; any other ordering will at best, give you different behavior. More likely, it breaks.

What you are trying to do is create a pipeline. Python has a very simple mechanism for doing that: call expressions. Here's what that would look like:

```<code>def a(self):
  return select_kbest(vectorize(twitter_cache(('me', '123'))))
</code>```

Or if that line grows too long, use dummy variables (still use meaningful names though!) to store intermediate results. Don't be afraid to go with a simple solution!

"Simple is better than complex."

--The Zen of Python

People say that the advantage of decorators is that they consolidate knowledge, reduce repetition, but regular functions do the same thing, and (when applicable) are often simpler. Also, since you can do foo(bar(...)) on a single line, it can (and usually does) result in fewer lines. The main difference is that with decorators, the additional code goes before the def keyword instead of after. Is that really an advantage? I tend to think not.

In the case of author and export, the same things cannot be accomplished using code in the def body, because such code doesn't get executed until the function is called. Whereas, decorators get executed when the function is defined.

I think logging is is closer to crossing the line into "inapprorpiate use of decorators" territory, but I think it's still ok: they do change behavior, but the difference is minor (e.g. it wouldn't reasonably break any existing tests), and you (generally) still get order independence.

Pre- and post- condition checkers (e.g. arg 1 is of type Foo) get even closer to the line (and perhaps cross it). If only good calls ever occur, then, they have no effect, and you generally get order independence. But the behavior change is more significant than just logging.

Then, there are what I call "prepare" decorators, which take things one step further. E.g.

```<code>def require_login(handler):
    @functools.wraps(handler)
    def decorated(request):
        session = decode_session(request.cookies['session'])
        if not session.user_is_logged_in:
            raise HttpError(403)

        # Warning: side effect!
        request.session = session
        return handler(request)
    return decorated
</code>```

require_login is sort of like a pre-condition checker, in that it raises an exception if the input fails to meet some condition. But it also does some work on behalf of handler: it sets the session attribute on request before forwarding request to handler. This makes require_login harder to understand. No longer does the original function take a regular Request: it takes a request with a session tacked on. Furthermore, The same thing can be accomplished without decorators:

```<code>def handle(request):
    session = require_login(request.cookies['session'])
    # if require_login did not raise an HttpError, then session must be that
    # of a logged in user. Proceed as before.
</code>```

As with decorators, this solution requires only one additional line, but only uses basic call technology.

OwnerDisplayName: Matti Lyra

Body:
In general, inheritance is overused. Remember: inheritance is all about the "is a" relationship; modeling hierarchical relationships. Therefore, ask yourself, "Is an ExperimentA a SelectKBest?". That question is nonsensical. SelectKBest doesn't even name a thing; it's an imperative phrase (or the jamming together of one). But let's just say you changed the name to something like TopSelector. Then, the question becomes "Is an ExperimentA a TopSelector?". Again, that doesn't make sense (to me). Without knowing more about your app, it very much seems to be a categorical error. These types have nothing to do with each other. Therefore, inheritance is the wrong thing to use.

This does not mean that decorators are right either though.

Not really sure what decorator best practices are. I'd be wary of stacking lots of decorators. I suppose if they do things that are totally independent, then it's ok. E.g.

__all__ = []

def export(f):
   __all__.append(f.func_name)
   return f

def author(name):
    def decorate(f):
        f.author = name
        return f
    return decorate

@author('allyourcode')
@export
def SaveTheWorld():
    # Left as an exercise to the reader.

One thing that tells us that export and author are independent is that you can apply them in any order, and the result is the same: 'SaveTheWorld' is appended to __all__ and SaveTheWorld.author == 'allyourcode'.

I seem to recall hearing that Guido likes this rule: if decorators stop working when you apply them in a different order, then it's bad.

In EXAMPLE2, order is very significant; any other ordering will at best, give you different behavior. More likely, it breaks.

What you are trying to do is create a pipeline. Python has a very simple mechanism for doing that: call expressions. Here's what that would look like:

def a(self):
  return select_kbest(vectorize(twitter_cache(('me', '123'))))

Or if that line grows too long, use dummy variables (still use meaningful names though!) to store intermediate results. Don't be afraid to go with a simple solution!

"Simple is better than complex."

--The Zen of Python

People say that the advantage of decorators is that they consolidate knowledge, reduce repetition, but regular functions do the same thing, and (when applicable) are often simpler. Also, since you can do foo(bar(...)) on a single line, it can (and usually does) result in fewer lines. The main difference is that with decorators, the additional code goes before the def keyword instead of after. Is that really an advantage? I tend to think not.

In the case of author and export, the same things cannot be accomplished using code in the def body, because such code doesn't get executed until the function is called. Whereas, decorators get executed when the function is defined.

I think logging is is closer to crossing the line into "inapprorpiate use of decorators" territory, but I think it's still ok: they do change behavior, but the difference is minor (e.g. it wouldn't reasonably break any existing tests), and you (generally) still get order independence.

Pre- and post- condition checkers (e.g. arg 1 is of type Foo) get even closer to the line (and perhaps cross it). If only good calls ever occur, then, they have no effect, and you generally get order independence. But the behavior change is more significant than just logging.

Then, there are what I call "prepare" decorators, which take things one step further. E.g.

def require_login(handler):
    @functools.wraps(handler)
    def decorated(request):
        session = decode_session(request.cookies['session'])
        if not session.user_is_logged_in:
            raise HttpError(403)

        # Warning: side effect!
        request.session = session
        return handler(request)
    return decorated

require_login is sort of like a pre-condition checker, in that it raises an exception if the input fails to meet some condition. But it also does some work on behalf of handler: it sets the session attribute on request before forwarding request to handler. This makes require_login harder to understand. No longer does the original function take a regular Request: it takes a request with a session tacked on. Furthermore, The same thing can be accomplished without decorators:

def handle(request):
    session = require_login(request.cookies['session'])
    # if require_login did not raise an HttpError, then session must be that
    # of a logged in user. Proceed as before.

As with decorators, this solution requires only one additional line, but only uses basic call technology.


问:
At what point should you collapse many parameters into (e.g.) struct to improve readability in function headers?
While making a struct creates some overhead at run-time, packaging a bunch of frequently-used-together variables can dramatically increase code readability.  How do you balance the two?  I was just asked to "unroll" a struct that contained 12 variables, which now makes calls to the function header monolithic; it seems poor style and I wanted to know what others thought.</p>

答:
How many functions do you have that uses those parameters?

If you have 4 functions that all take the same 12 parameters, it's a sign that you probably should bundle those into a cohesive set.

If you have 4 functions that use say... 8 of the parameters, then maybe those 8 should be bundled up.

But this is rather missing a little bit of the point. Bundling into a struct is not your only option. You can also break up the function so that instead of one big function needing 12 parameters, you have 8 more focused ones that need one or two parameters. Smaller functions are easier to test, easier to reuse, easier to write, easier to maintain.


答:
Keep in mind that typically the solution is not always collapsing some of the arguments into a distinct data structure. Most of the times you should split the functions into multiple ones because probably it's the function itself that does multiple things.

I remember Uncle Bob in Clean Code saying there should be at most 2 and only in special cases 3 arguments to a function. This might be very difficult to achieve all the time (take for example functions with timeouts where the timeout and timeunit take 2 arguments).

On the other hand Code Complete is not so rigorous, saying there shouldn't be more than 7 but emphasizing on the fact that in higher-level languages this can be avoided.

Title: At what point should you collapse many parameters into (e.g.) struct to improve readability in function headers?

Body: While making a struct creates some overhead at run-time, packaging a bunch of frequently-used-together variables can dramatically increase code readability.  How do you balance the two?  I was just asked to "unroll" a struct that contained 12 variables, which now makes calls to the function header monolithic; it seems poor style and I wanted to know what others thought.</p>


答:
For me following three are important -

Loyalty : All things can be taught to loyal people.

Commitment : Does he think Job as a Mission or Drudgery.

Integrity : Values shape up all other skills, to differentiate one works hard to acquire rest of the skills.

About Programming, I think the following things matter:

Problem Solving Skills (Aptitude)

In depth Knowledge of Programming languages

Experience in atleast one Project in a specific language

A good(atleast OKAY) record while pursuing Computer Science(or equivalent) education.

Title: What are the skills you look for when hiring a fresher/newbie for developement?


问:
What is a "side effect?"
I haven’t clearly understood the concept of side effect.

What is side effect in programming?

Is it programming language dependent?

Is there such a thing as external and internal side effects?

Please give some example of causes that create side effects.

答:
I think that the existing answers are quite good. I would like to elaborate on some aspects that IMO have not been stressed enough.

In mathematics a function is just a mapping from a tuple of values to a value. So, given a function f and a value x, f(x) will always be the same result y. You may well replace f(x) with y everywhere in an expression and nothing will change.

What is called a function (or procedure) in many programming language is a construct (piece of code) that can be executed because:

It computes a function in the mathematical sense, i.e. given input values, it returns a result, or

It produces some effect, e.g. prints something to the screen, changes a value on a database, launches missiles, sleeps for 10 seconds, sends an SMS.

So effects can be related to state but also to other aspects like firing a missile or pausing execution for a few seconds.

The term side-effect may sound negative but normally the effect of calling a function is the very purpose of the function itself. I suppose that, since the term function was originally used in Mathematics, computing a value is considered to be the primary effect of a function whereas any other effects are considered side-effects.
Some programming languages use the term procedure to avoid confusion with functions in the mathematical sense.

Note that

Some procedures are useful for both their return value and their side-effect.

Some procedures only compute a result value and have no other effects. They are often called pure functions because all they do is compute a function in the mathematical sense.

Some procedures, e.g. sleep() in Python, are only useful for their (side) effects, . These are often modeled as functions that return a special value None, or unit or () or ..., which simply indicates that the computation has terminated correctly.

Title: What is a "side effect?"


问:
Loop runtime question
I had an exam today and I feel that I did pretty well, except I could not for the life of me figure out what appears to be an unbelievably simple question.

We were asked to give theta notation run times for a few programs(with input size n), and this was one of them:

```<code>int sum = 0;
for int i = 0; i < n; i++
   for int j = 0; j < i; j++
      sum++
</code>```

So I know iterating from 0 to n on both loops would render a O(n2) run time... but with the second loop only iterating to the first loop control variable, I would assume it must be faster... because the second loop never even reaches n iterations until the very last loop-through?

I'm gonna freak out if its O(n2) and I over thought this...

答:
I'm gonna freak out if its O(n2) and I over thought this...

Don't freak out -- too much.

The outer loop will execute n times. The inner loop will execute an average of about (n/2) times. This results in a total of n2/2 evaluations - or in more precise notation, runtime of O(n2).

Also this is pretty easy to verify by writing a short/simple program.

Title: Loop runtime question


答:
The complexity class is O(n²).

Visual explanation

Imagine a n·n square which lists all the values j takes on. We remove the diagonal (which has n entries) and the upper right half because j will never be larger or equal to i. We are then left with an area of (n² - n)/2.

```<code> i  | values of j     | no of j values
----+-----------------+---------------
 0  | · · · · ·  ⋯  · |  0
 1  | 0 · · · ·  ⋯  · |  1
 2  | 0 1 · · ·  ⋯  · |  2
 3  | 0 1 2 · ·  ⋯  · |  3
 4  | 0 1 2 3 ·  ⋯  · |  4
 :  | : : : :    :  : |  :
n-1 | 0 1 2 3 ⋯ n-2 · | n-1
                       =====
                  SUM: (n² - n)/2
</code>```

Mathematical explanation

The outer loop executes n times, the inner loop i times. We can write the number of executions of the inner loop body as ∑mi=1 i with m = n-1. The sum of all natural numbers up to including m can also be written as m·(m + 1)/2 (the formula for triangular numbers), which leads to n(n-1)/2.

Conclusion

Using either method, we can determine that the nested loops have a complexity of O((n² - n)/2) = O(n²).

Title: Loop runtime question

Body:
I had an exam today and I feel that I did pretty well, except I could not for the life of me figure out what appears to be an unbelievably simple question.

We were asked to give theta notation run times for a few programs(with input size n), and this was one of them:

```<code>int sum = 0;
for int i = 0; i < n; i++
   for int j = 0; j < i; j++
      sum++
</code>```

So I know iterating from 0 to n on both loops would render a O(n2) run time... but with the second loop only iterating to the first loop control variable, I would assume it must be faster... because the second loop never even reaches n iterations until the very last loop-through?

I'm gonna freak out if its O(n2) and I over thought this...

Body:
The complexity class is O(n²).

Visual explanation

Imagine a n·n square which lists all the values j takes on. We remove the diagonal (which has n entries) and the upper right half because j will never be larger or equal to i. We are then left with an area of (n² - n)/2.

 i  | values of j     | no of j values
----+-----------------+---------------
 0  | · · · · ·  ⋯  · |  0
 1  | 0 · · · ·  ⋯  · |  1
 2  | 0 1 · · ·  ⋯  · |  2
 3  | 0 1 2 · ·  ⋯  · |  3
 4  | 0 1 2 3 ·  ⋯  · |  4
 :  | : : : :    :  : |  :
n-1 | 0 1 2 3 ⋯ n-2 · | n-1
                       =====
                  SUM: (n² - n)/2

Mathematical explanation

The outer loop executes n times, the inner loop i times. We can write the number of executions of the inner loop body as ∑mi=1 i with m = n-1. The sum of all natural numbers up to including m can also be written as m·(m + 1)/2 (the formula for triangular numbers), which leads to n(n-1)/2.

Conclusion

Using either method, we can determine that the nested loops have a complexity of O((n² - n)/2) = O(n²).


问:
Integer sign and compilation via C
I'm writing a compiler that uses the time-honored strategy of using a C compiler as the back end, and I'm trying to figure out exactly how to handle integer sign.

I'm using machine word integers as the default (translating into intptr_t and uintptr_t in the generated C), and while for myself I would prefer to make the default unsigned, I probably don't have much choice about making it signed just because that expectation is so widely ingrained.

I'm defining the result of integer overflow to be wraparound (at least by default, might add an option to throw an exception later), but in C, signed integer overflow is undefined behavior, so I can't just emit code that performs signed integer arithmetic. It seems to me there are two options:

Emit signed integers, but convert to unsigned for all arithmetic operations except division and right shift (these are the only ones where the difference matters, and also the only ones that can't overflow - edit: except for INT_MIN / -1; I had been considering that in the same category as division by zero, but of course it is strictly speaking an overflow).

Emit unsigned integers, but convert to signed for division (resisting the temptation to make division of negative numbers undefined behavior), right shift and comparison other than equality.

Emit signed integers anyway, use -fwrapv when using GCC as the backend, and hope other C compilers either don't take advantage of signed overflow being undefined, or provide a switch to disable such optimizations.

Does the third option work (e.g. are there any C compilers where you can't make signed overflow wrap)? If not, which of the first two is likely to involve less code and opportunity for error? Is there anything I'm missing?

答: I would suggest using unsigned arithmetic for everything, using some conditionally-defined type definitions to ensure that nothing unexpectedly gets promoted to int.  To compare two "signed" 32-bit values, xor them both with 0x80000000U and then compare as unsigned.  For signed division, use a library method to process both operands as positive, so that you will then use unsigned division.

Title: Integer sign and compilation via C