问:
How to organize methods that check username/email availability in a REST API?
I am developing a RESTful API in my project, but I do not have experience on that. To fill these gaps I've been watching some videos, mainly from Apigee, which are great.
One situation brings a lot of discussion on my project and I hope you can help me clear it out. The client using the API is able to create a user by posting to my /Users url, but it has some requirements as: name format, username availability, email availability, valid region and many others.
I can easily validate the name format in my client app, that would be easy. The problem is when it comes to availability (mainly if the email and the user name are available to be user or are already taken).
We have two different lines of thoughts on my team:

the first one would break each verification in a different url, something like
/Users/EmailAvailable and /Users/UsernameAvailable
ou
/Available/Email and /Available/Username

They claim that it would make the interface cleaner (more intuitive) and would also keep cohesion, since one method has only one responsibility.

The second line of thought is to have only one URL
/User/Verify
and it will verify either the username, email or both, depending on the JSON it receives. They claim that it would only require one trip to the server and that cohesion is not a problem because, since the URLs are not necessarily mapped to methods, they can divide the calls into methods that do one thing each.
They also claim that the interface shouldn't care about cohesion

My questions:
1- Are these arguments about cohesion from the second line of though valid?
2- How would you do? (Either one of those or any other that you know of)

thanks!

答:
You can't validate and create something atomically with several Rest Api requests.
But if you must really do it, a HEAD request to /users/?[email=user@example.com|user=aUsername]
should return 404 if it's not already exists. That way you don't put adjective (available)
or verb (verify) in the Url. Keep it simple.

I would POST User to /users and if username or email had been used, return 409 (conflict)
with explanation either username or email is already exists.


问:
What's the cheapest way to host hobby projects?
What's the best place to put your hobby web projects(the web app itself, not the code) ? Typically, the projects are such that:

a) I just want to test out an interesting idea without exploring the business angle to it, just to see how people take it.

b) I don't expect a lot of traffic

c) I don't want to scale immediately

d) I don't want to be tied down to one technology(I want to do different projects to get familiar with various web stacks, langs and libs)

Google app engine seems very restrictive for such exploratory stuff ... Restrictions like no outbound request can go beyond 10 seconds and every request has to return with 30 seconds, etc. piss me off, I know they are needed for scale, but I would like them to be optional.

Amazon EC2 micro nodes are free for a year. But they ask for credit card information which I am not sure if I want to give away when I'm not paying initially.

What other free/cheap alternatives do I have?

答:
Heroku is a good alternative for Ruby on Rails projects.

a cloud platform as a service (PaaS) supporting several programming languages. Heroku was acquired by Salesforce.com in 2010. Heroku, one of the first cloud platforms, has been in development since June 2007, when it supported only the Ruby programming language, but has since added support for Java, Node.js, Scala, Clojure and Python and (undocumented) PHP and Perl. The base operating system is Debian or, in the newest stack, the Debian-based Ubuntu...

You can push to Heroku straight from Github, which makes deployment ridiculously easy.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Extreme Programming for a single developer
I've been working with some basic extreme programming concepts for the last two weeks, for a small scale, for-profit, multiplayer, arcade game. I've spent a week developing user stories and determining requirements to create a release plan. I've also spent a week coding and applying the first iteration plan I came up with. I've identified a few of the obviously useful concepts for a single developer.

Continuous Integration

Never Add Functionality Early

Test Driven Development

Choose a System Metaphor

Use a single Integration Point

Test out all bugs

Constantly refactor

Set a sustainable pace

Simplicity

Frequent Releases

I'm curious if I'm missing anything in particular that might be suited to working with a single developer project?

Also, in this light given the idea of simplicity and test driven development, is it better to use established, feature-rich, ready made platforms?

Or should I work from the ground up, when feasible, to avoid running into the issues presented with rules such as constantly refactoring and never adding functionality early?

答:
Ultimately,   Extreme Programming is about a set of practices and methodologies that lead to improved business value.  The best illustration of this that I have found is from http://c2.com/cgi/wiki?ExtremeProgrammingEnablingChart

Everything in blue is part of the core of XP.

There are parts of it that are at the outside of it that help enable things within the blue area and are part of XP as a whole, but not critical to it.  Note that I am personally not an XP practitioner and I've read a fair amount of criticism of people "almost" following XP that various people have said isn't XP.  Lets set that aspect of the dogma of XP aside for a bit and look at what we have.

Realize that one of the first and for most things is to have a commitment to the process from the customer.  A key component of XP is the customer involvement.  This shows up in a number of the spots such as release planning, small releases, offsite customer evaluation.  These are things that your customers will need to subscribe to if you are going to be successful at XP as a solo developer.  If they ask instead for a design and then a development period and then testing and such, you won't have the commitment from them to go further.

XP doesn't mean no planning.  There are several points in this where planning is part of it - prioritization, user story estimation, iteration planning, and task definition.  Even though you are one developer on this, these are things that you will need to work with your customer on delivering.

Points such as collective ownership of the code and pair programming are things that involve more than one.  Deciding upon things such as coding standards are much easier, but it doesn't mean you don't have to follow them.   Collective code ownership still applies - its just that the ownership is also the next developer - don't write code that is for you and you alone.  Note that this is in some degree of conflict with the 'code reveals all intention' that is enabled by pair programming - you don't have that person to check that you are writing maintainable code so documentation of the code is also critical.

Apart from those caveats, many of the XP design principles still apply.  Things such as test first design, continuous integration, meetings with the customer, refactoring, YAGNI, spike solutions - those call can be done solo.

Realize that solo XP takes as much or more discipline as regular XP.  XP is often considered a high discipline methodology in that it requires people to maintain rigorous adherence to the best practices that it tries to embody.  When you don't have a coach or other people to support that discipline needed it can fall away into just a hodgepodge of practices that bear some resemblance to XP.

Related reading:

Variations on a Theme of XP (Martin Fowler)

Extreme Programming (various at c2)

Extreme Programming For One (various at c2)

I'd like to pull out a quote from the first of the c2 links:

Noted Perl Language luminary, and mad scientist, Damian Conway believes that Extreme Programming is actually a misnomer. Since it embodies many of the good programming practises that programmers are taught but almost certainly ignore, he believes that it should really have been called Ultra Conservative Programming


答:
Unless you can those REST methods independently in other parts of the system, I would have the one REST endpoint which accepts a JSON payload containing all the data...two fields in this case. Of course you would refactor this out on the backend should you need to open up a second endpoint which will allow you to check separately. One connection also works nicely for mobile devices.

If you plan on checking for the availability of e-mails, ensure you use a captcha verification image. Depending on your budget and your UX requirements, you might want to introduce captcha only if more than n number of e-mail checks are done within a certain time frame.

Captcha is faily easy to integrate. There are a few providers out there, but the most popular one seems to be https://www.google.com/recaptcha/captcha

Title: How to organize methods that check username/email availability in a REST API?

Body:
I am developing a RESTful API in my project, but I do not have experience on that. To fill these gaps I've been watching some videos, mainly from Apigee, which are great.
One situation brings a lot of discussion on my project and I hope you can help me clear it out. The client using the API is able to create a user by posting to my /Users url, but it has some requirements as: name format, username availability, email availability, valid region and many others.
I can easily validate the name format in my client app, that would be easy. The problem is when it comes to availability (mainly if the email and the user name are available to be user or are already taken).
We have two different lines of thoughts on my team:

the first one would break each verification in a different url, something like
/Users/EmailAvailable and /Users/UsernameAvailable
ou
/Available/Email and /Available/Username

They claim that it would make the interface cleaner (more intuitive) and would also keep cohesion, since one method has only one responsibility.

The second line of thought is to have only one URL
/User/Verify
and it will verify either the username, email or both, depending on the JSON it receives. They claim that it would only require one trip to the server and that cohesion is not a problem because, since the URLs are not necessarily mapped to methods, they can divide the calls into methods that do one thing each.
They also claim that the interface shouldn't care about cohesion

My questions:
1- Are these arguments about cohesion from the second line of though valid?
2- How would you do? (Either one of those or any other that you know of)

thanks!


答:
This really depends on what this is. Is it a web app? Is it a server app? How many people do you need to serve initially?

If its a web app then just find a good free web host. Any will do, and most have more than enough bandwidth and disk space for beta testing of an app.

If its a server app, why not host it yourself or on a friends server? This way its something you can control, your have practically no limits on what you can do (scalability comes later), and its (mostly) free.

You can simply try this on your/someone elses server and see if people like it. Then once you get the ball rolling, you can start thinking about getting a real server somewhere

Title: What's the cheapest way to host hobby projects?

Body:
What's the best place to put your hobby web projects(the web app itself, not the code) ? Typically, the projects are such that:

a) I just want to test out an interesting idea without exploring the business angle to it, just to see how people take it.

b) I don't expect a lot of traffic

c) I don't want to scale immediately

d) I don't want to be tied down to one technology(I want to do different projects to get familiar with various web stacks, langs and libs)

Google app engine seems very restrictive for such exploratory stuff ... Restrictions like no outbound request can go beyond 10 seconds and every request has to return with 30 seconds, etc. piss me off, I know they are needed for scale, but I would like them to be optional.

Amazon EC2 micro nodes are free for a year. But they ask for credit card information which I am not sure if I want to give away when I'm not paying initially.

What other free/cheap alternatives do I have?


问:
What is a good strategy for binding view objects to model objects in C++?
Imagine I have a rich data model that is represented by a hierarchy of objects.

I also have a view hierarchy with views that can extract required data from model objects and display the data (and allow the user to manipulate the data).

Actually, there could be multiple view hierarchies that can represent and manipulate the model (e.g. an overview-detail view and a direct manipulation view).

My current approach for this is for the controller layer to store a reference to the underlying model object in the View object. The view object can then get the current data from the model for display, and can send the model object messages to update the data. View objects are effectively observers of the model objects and the model objects broadcast notifications when properties change.

This approach allows all the views to update simultaneously when any view changes the model.

Implemented carefully, this all works. However, it does require a lot of work to ensure that no view or model objects hold any stale references to model objects. The user can delete model objects or sub-hierarchies of the model at any time. Ensuring that all the view objects that hold references to the model objects that have been deleted is time-consuming and difficult.

It feels like the approach I have been taking is not especially clean; while I don't want to have to have explicit code in the controller layer for mediating the communication between the views and the model, it seems like there must be a better (implicit) approach for establishing bindings between the view and the model and between related model objects.

In particular, I am looking for an approach (in C++) that understands two key points:

There is a many to one relationship between view and model objects

If the underlying model object is destroyed, all the dependent view objects must be cleaned up so that no stale references exist

While shared_ptr and weak_ptr can be used to manage the lifetimes of the underlying model objects and allows for weak references from the view to the model, they don't provide for notification of the destruction of the underlying object (they do in the sense that the use of a stale weak_ptr allows for notification), but I need an approach that notifies the dependent objects that their weak reference is going away.

Can anyone suggest a good strategy to manage this?

答:
If I understand your design correctly, you have a model-view model.

To improve it, you can use MVC design with observer pattern, where :

controllers are just connecting models->views and views->models signals to slots

views are showing what they need to show, listen to relevant events from the model in order to update the view, and forwards the user's interaction to models

models are implementing the logic. They handle user's interaction, and sends events to views to inform them of changes

This way, if you wish to destroy a model, you can do it without much hastle. You will also have to break connections in the controller.

Here you can see how I implemented MVC in qt5. It may evolve into something useful in far future, but for now it is just for demonstration purposes :)


答:
I'd just get a cheap VPS at any reputable provider. This gives you full control over the server / language stack, allows you to work with any kind of storage or DB and can easily be re-loaded if you want to completely switch technologies to work on something else (for instance, going from Linux to Windows or back).

Something in the range of $15 could satisfy the needs of multiple hobby projects .. and I think most people would have no problem spending that on a hobby that they found enjoyable and worth while.

This also ensures that you have full control of your data, as well as support if you need it.


问:
How much warnings in C to enable?
This is a tiny project of about 2000LOC. It is being compiled with -Wall. Now, I tried adding -Wextra. Two things happened:

Some minor but valid warnings popped up, e.g. Comparing signed with unsigned

Some minor but false warnings popped up, e.g. Unused function parameter.

Those functions implement agreed-upon prototypes. But the extra parameters are really not needed for now.

However the unfixable warnings pollute the build log and could hide a much more dangerous warning.

Should the -Wextra be retained or removed? How can a compromise be made for the most robust code development in the future?

答:
nearly all warnings have workarounds to silence them in specific circumstances

the unsigned vs. signed comparison means you need to double check the types

unused parameter warnings can be silenced by adding a (void)arg; statement in the function, this is a noop and will document that the argument is unused

failing that you can surround the warning emitting code with #pragmas that disable and re-enable those warnings as needed

Title: How much warnings in C to enable?


答:
There are several ways to get rid of those harmless warnings, without also disabling the useful ones.

The -Wall and -Wextra warning options enable a whole bunch of warnings that can also be enabled/disabled individually. To avoid generating the 'unused parameter' warnings, you can use

```<code>-Wall -Wextra -Wno-unused-parameter
</code>```

If it is only for a limited number of arguments in a limited number of functions that the 'unused parameter' warning is known to be spurious, you can suppress the warning on a case-by-case basis

Either by using the parameter, if only in a no-op statement like

```<code>(void)arg;
</code>```

Or, if you don't mind GCC-specific code, by adding the unused attribute to the relevant parameters

```<code>void foo(int arg __attribute__((unused)) )
{ /* ... */ }
</code>```

Title: How much warnings in C to enable?

Body:
This is a tiny project of about 2000LOC. It is being compiled with -Wall. Now, I tried adding -Wextra. Two things happened:

Some minor but valid warnings popped up, e.g. Comparing signed with unsigned

Some minor but false warnings popped up, e.g. Unused function parameter.

Those functions implement agreed-upon prototypes. But the extra parameters are really not needed for now.

However the unfixable warnings pollute the build log and could hide a much more dangerous warning.

Should the -Wextra be retained or removed? How can a compromise be made for the most robust code development in the future?

Body:
There are several ways to get rid of those harmless warnings, without also disabling the useful ones.

The -Wall and -Wextra warning options enable a whole bunch of warnings that can also be enabled/disabled individually. To avoid generating the 'unused parameter' warnings, you can use

-Wall -Wextra -Wno-unused-parameter

If it is only for a limited number of arguments in a limited number of functions that the 'unused parameter' warning is known to be spurious, you can suppress the warning on a case-by-case basis

Either by using the parameter, if only in a no-op statement like

(void)arg;

Or, if you don't mind GCC-specific code, by adding the unused attribute to the relevant parameters

void foo(int arg __attribute__((unused)) )
{ /* ... */ }


问:
What is the real responsibility of a class?
I keep wondering if it is legitimate to use verbs that are based on nouns in OOP.

I came across this brilliant article, though I still disagree with the point it makes.

To explain the problem a bit more, the article states that there shouldn't be, for instance, a FileWriter class, but since writing is an action it should be a method of the class File. You'll get to realize that it's often language dependent since a Ruby programmer would likely be against the use of a FileWriter class (Ruby uses method File.open to access a file), whereas a Java programmer wouldn't.

My personal (and yes, very humble) point of view is that doing so would break the Single Responsibility principle. When I programmed in PHP (because PHP is obviously the best language for OOP, right?), I would often use this kind of framework:

```<code><?php

// This is just an example that I just made on the fly, may contain errors

class User extends Record {

    protected $name;

    public function __construct($name) {
        $this->name = $name;
    }

}

class UserDataHandler extends DataHandler /* knows the pdo object */ {

    public function find($id) {
         $query = $this->db->prepare('SELECT ' . $this->getFields . ' FROM users WHERE id = :id');
         $query->bindParam(':id', $id, PDO::PARAM_INT);
         $query->setFetchMode( PDO::FETCH_CLASS, 'user');
         $query->execute();
         return $query->fetch( PDO::FETCH_CLASS );
    }

}

?>
</code>```

It is my understanding that the suffix DataHandler doesn't add anything relevant; but the point is that the single responsibility principle dictates us that an object used as a model containing data (may it be called a Record) shouldn't also have the responsibility of doing SQL queries and DataBase access. This somehow invalidates the ActionRecord pattern used for instance by Ruby on Rails.

I came across this C# code (yay, fourth object language used in this post) just the other day:

```<code>byte[] bytes = Encoding.Default.GetBytes(myString);
myString = Encoding.UTF8.GetString(bytes);
</code>```

And I gotta say that it doesn't make much sense to me that an Encoding or Charset class actually encodes strings. It should merely be a representation of what an encoding really is.

Thus, I would tend to think that:

It is not a File class responsibility to open, read or save files.

It is not a Xml class responsibility to serialize itself.

It is not a User class responsibility to query a database.

etc.

However, if we extrapolate these ideas, why would Object have a toString class? It's not a Car's or a Dog's responsibility to convert itself to a string, now is it?

I understand that from a pragmatic point of view, getting rid of the toString method for the beauty of following a strict SOLID form, that makes code more maintainable by making it useless, is not an acceptable option.

I also understand that there may not be an exact answer (which would more be an essay than a serious answer) to this, or that it may be opinion-based. Nevertheless I would still like to know if my approach actually follows what the single-responsibility principle really is.

What's a class's responsibility?

答:
[Note: I'm going to be talking about objects here. Objects is what object-oriented programming is about, after all, not classes.]

What the responsibility of an object is depends mostly on your domain model. There are usually many ways to model the same domain, and you will choose one way or the other based on how the system is going to be used.

As we all know, the "verb/noun" methodology that is often taught in introductory courses is ridiculous, because it depends so much on how you formulate a sentence. You can express almost anything as either a noun or a verb, in either an active or a passive voice. Having your domain model depend on that is wrong, it should be a conscious design choice whether or not something is an object or a method, not just an accidental consequence of how you formulate the requirements.

However, it does show that, just like you have many possibilities of expressing the same thing in English, you have many possibilities of expressing the same thing in your domain model … and none of those possibilities is inherently more correct than the others. It depends on the context.

Here is an example which is also very popular in introductory OO courses: a bank account. Which is typically modeled as an object with a balance field and a transfer method. In other words: the account balance is data, and a transfer is an operation. Which is a reasonable way to model a bank account.

Except, that's not how bank accounts are modeled in real-world banking software (and in fact, it's not how banks work in the real world). Instead, you have a transaction slip, and the account balance is computed by adding (and subtracting) up all the transaction slips for an account. In other words: the transfer is data and the balance is an operation! (Interestingly, this also makes your system purely functional, since you never need to modify the balance, both your account objects and the transaction objects never need to change, they are immutable.)

As to your specific question about toString, I agree. I very much prefer the Haskell solution of a Showable type class. (Scala teaches us that type classes fit beautifully with OO.) Same with equality. Equality is very often not a property of an object but of the context in which the object is used. Just think about floating point numbers: what should the epsilon be? Again, Haskell has the Eq type class.


问:
Should experimental code be preserved?
Am am working on a small project for a USB device firmware.

I started from a working example, and am gradually adding new functionality and testing things. However, the new functionality is not all intended to be used in the final project. I am writing it to learn how to do things on this concrete platform, and fixing unexpected problems in the process (for example, on of my test PCs had non-functional USB ports).

What should I do with the old code? The code is version controlled, of course. I see two possibilities:

Change old code into new one. An example here would be, when moving from having a Loopback over the UART (for testing purposes), and moving to more sensible use of the UART, change the DMA code to read not from the input of the UART, but from the CPU buffer, that is to be sent out.

Use a bunch of #if statements to make the source code configurable, so that any version of the code can be compiled by only providing the correct #define.

If the latter approach is recommended, where is the dividing line? I can't keep every line of code that I write, hiding it behind an #if.

答:
If you are using source control then let it live in there.

To find it more easily later you should provide a reference to the revision with the prototype in the relevant bug report where the enhancement is discussed.

Title: Should experimental code be preserved?


问:
Building an application around a theoretical currency
I'm currently doing an application design that involves sale of service. The application will ultimately be used internationally and will need to adjust prices based on user location.

Is it a good idea to store / work with all prices in an absolute unit? For example - credits. And I can specify conversion rules like 1 credit = 1 USD. What scenarios would I need to be careful about if I do this (and should I be doing this)?

One thing I can think of is problems during auditing if I change my conversion rules periodically. In which case I'll need to start storing conversion rules by date and the conversion process will also require the time of transaction to give the correct amount in any currency for that time.

Am I complicating this too much?

答:
You're both over and under-complicating it. You're over-complicating it for the users, who now have to convert things between credits and their local currency in their head, and under-complicating it for yourself. Things are not priced identically around the world, even once you account for exchange rates. Heck, things are not priced identically around what I assume is your home country of the US, tax rates change on a per-state and per-city level and for a payment system this has to be taken into account.

Simply put, this will increase the difficulty for the user (and thus decrease the likelihood they'll actually give you that money) and not significantly improve your own situation. Systems of "points" instead of real currency are typically used not to simplify things, but to hide the true cost of items, and only really work well in situations where there can be no competition. See theme parks, proprietary video game systems, casinos, et cetera.


答:
I don't think you can do this with an artificial currency.

At some point your application needs to interact with the "real" world of accounting, and the transactions need to be auditable ... in terms of an actual currency.  The tax man wants his cut of the action ... in a particular currency.  And people need to pay definite amount of money in real currencies.

The simplest way to do this is to nominate your prices in specific currencies ... and let PayPal or the Credit Card company ... or the customer's bank deal with the problem of converting the customer's money to the currency you require payment in.

(And note that if you accept payment in multiple currencies, you will end up paying for the currency conversions rather than the customer!)

Title: Building an application around a theoretical currency

Body:
I'm currently doing an application design that involves sale of service. The application will ultimately be used internationally and will need to adjust prices based on user location.

Is it a good idea to store / work with all prices in an absolute unit? For example - credits. And I can specify conversion rules like 1 credit = 1 USD. What scenarios would I need to be careful about if I do this (and should I be doing this)?

One thing I can think of is problems during auditing if I change my conversion rules periodically. In which case I'll need to start storing conversion rules by date and the conversion process will also require the time of transaction to give the correct amount in any currency for that time.

Am I complicating this too much?


问:
Sorting an array of numbers with decimal places
Suppose I have an array of float values in the following format:

```<code>{ 1.34, 1.15, 1.1, 1.2, 1.26, 1.10, 1.20, 1.17 }
</code>```

Suppose they have been provided by user input (or some other mechanism), where the user takes "1.1" to actually mean "1.01" - meaning that it is separate from "1.10".

Using a standard sorting algorithm (bubble sort, quick sort, or some framework specific sort) is going to result in an array which should look similar to the following:

```<code>{ 1.1, 1.10, 1.15, 1.17, 1.2, 1.20, 1.26, 1.34 }
</code>```

However, the required output array would be the following:

```<code>{ 1.1, 1.2, 1.10, 1.15, 1.17, 1.20, 1.26, 1.34 }
</code>```

I'm thinking that the way to do this would be to iterate through the array before sorting and:

check whether the value of has N decimal places

if so, elevate to M (N + 1) decimal places - add a leading 0?

This would lead to two arrays, one containing values with N or M number decimal places (raw user input) and one containing all values with M number decimal places ("sanitised" user input). Which would mean that sorting the array containing values with M decimal places would provide the required result.

Are there any other ways to do this? I'm looking for faster algorithms, or those with a lower overhead.

I see this as being a common problem domain, and I'm going to guess that there are a multitude of ways to fix this. What are some of the other algorithms that can be used to attain the required result.

答:
A bit of nitpicking: If some values have more significant digits than others, than what you have is not floats. It's strings intended to be interpreted as floats, but you do have to interpret them every time you access them, and that's precisely the issue here.

Basically you have two options. Either you use a bog-standard sort algorithm and just program your comparator routine so that it performs Float.parseFloat() before calculating anything with its arguments - or you do the parsing once and for all in a separate step and store the numeric values somewhere, so you don't have to do it again.

Obviously, which solution is better depends on how often the comparator will be called. If your list is in random order, then most values will probably be touched more than once during the sorting, so pre-computing the values that you actually want to compare makes sense. But if the list tends to be near-sorted or if float parsing is too cheap to worry about (compared to the programming effort of adding a transformation step), then doing it on the fly during each comparison is better.

As always, which one is better in general can't be answered, and which one is better in your case can't be answered without profiling both solutions. Never assume - always measure.


问:
Considerations before rewriting a software component from scratch?
A piece of software is a patchwork of old and undocumented efforts. There are no comments, no documentation, and the code is hairy -- it involves Unix shell scripts that check for dummy files and then call SQL statements that call database procedures that modify data.

The original developers have left and we score a solid 2 on the Joel Test but I can raise it to at least 4 - yay...

The code is reasonably error-free, but we constantly need to add new features into it which is highly error-prone because of the state of the code, so the deadlines slip and the efforts rise.

We want to rewrite this software in order to reduce maintenance and development efforts. As part of the rewrite, we will introduce specs, comments, test cases -- all things that we currently don't have. It'll still be a bit complex afterwards, but no more than necessary.

This is not a BIG rewrite because we are not going to switch languages or frameworks; we'll still need shell scripts (but fewer) and database procedures (but fewer). The implications are also fairly simple because we're in control of the installation sites and we can fully replace the old code with the new code at the flick of a switch.

I know a rewrite is never good but I think these are reasonable counterarguments. Nevertheless, my concern is the typical danger of introducing brand new bugs instead of the old known ones, and also the danger of not implementing certain details because nobody even knows they exist or are needed.

How can I approach this rewrite in an efficient manner?

答:
I think you are overlooking something - you CAN'T rewrite it, because you've admitted you have no idea what it's doing!

It's great to realize that you'll need tests, but what are you going to test? You don't know what it does! How do you test it?

Before you can re-write, you have to spec it out, which means sitting down with the existing code for who knows how long and examining every SQL statement, every script and making sure you know what it's doing and why it's doing it. Especially important are identifying any weird side effects that turn out to be intended behaviors. All while maintaining the existing app as well. Good luck with that.

If you can't spend that kind of time on the spec (and most people can't), then you need to fix it piece by piece. When next you get a change order, identify what the function you are changing does, how it does it, write the tests, and re-write that piece.


答:
Your problem is that your "numbers" don't have decimal places. You have a string which consists of two integers which are separated by .. Parse them as two integers and write a custom comparer. The sorting algorithm can remain the same, you just need to pass in the comparer.

In C# such a comparer could look similar to this:

void Test()
{
    var data=new string[]{ "1.34", "1.15", "1.1", "1.2", "1.26", "1.10", "1.20", "1.17" };
    Array.Sort(data, VersionComparer);
    data.Dump();
}

static int VersionComparer(string s1, string s2)
{
    List<int> parts1 = s1.Split('.').Select(int.Parse).ToList();
    List<int> parts2 = s2.Split('.').Select(int.Parse).ToList();

    while(parts1.Count < parts2.Count)
        parts1.Add(0);
    while(parts2.Count < parts1.Count)
        parts2.Add(0);

    for(int i = 0; i < parts1.Count; i++)
    {
         if(parts1[i] < parts2[i])
             return -1;
         if(parts1[i] > parts2[i])
             return +1;
    }
    return 0;
}
```

Title: Sorting an array of numbers with decimal places

Body:
Suppose I have an array of float values in the following format:

```<code>{ 1.34, 1.15, 1.1, 1.2, 1.26, 1.10, 1.20, 1.17 }
</code>```

Suppose they have been provided by user input (or some other mechanism), where the user takes "1.1" to actually mean "1.01" - meaning that it is separate from "1.10".

Using a standard sorting algorithm (bubble sort, quick sort, or some framework specific sort) is going to result in an array which should look similar to the following:

```<code>{ 1.1, 1.10, 1.15, 1.17, 1.2, 1.20, 1.26, 1.34 }
</code>```

However, the required output array would be the following:

```<code>{ 1.1, 1.2, 1.10, 1.15, 1.17, 1.20, 1.26, 1.34 }
</code>```

I'm thinking that the way to do this would be to iterate through the array before sorting and:

check whether the value of has N decimal places

if so, elevate to M (N + 1) decimal places - add a leading 0?

This would lead to two arrays, one containing values with N or M number decimal places (raw user input) and one containing all values with M number decimal places ("sanitised" user input). Which would mean that sorting the array containing values with M decimal places would provide the required result.

Are there any other ways to do this? I'm looking for faster algorithms, or those with a lower overhead.

I see this as being a common problem domain, and I'm going to guess that there are a multitude of ways to fix this. What are some of the other algorithms that can be used to attain the required result.


问:
Service method, bean as an argument and mandatory attributes
There is a service:

```<code>createUser(User user)
</code>```

where you can create a new user, with so many attributes (name, address lines...). Now, some user attributes are mandatory. Other attributes are not mandatory (like nickname or image).

The problem is that, from the outside, you can't tell the difference (in compile time). You can't force yourself to set only mandatory fields; moreover, the list of mandatory fields can change in the future and your code will stop working (while still compiling).

So we can

createUser(int userId, String username...) - explode the bean properties and don't use bean as an argument. Now every change will be reflected in the API, but method signatures may become huge. Also, when overloading methods for various combinations of mandatory fields with non-mandatory - that can be a mess, too.

use multiple beans, and have methods like (given names are just illustrative) createUser(UserCoreData user), createUser(UserFull user) but that still would not help much.

or have service for storing mandatory User data and then having additional services for storing additional, non-mandatory data.

(EDITED) or to split User into logical components (ie smaller beans) Address, DateFrom... and use those in service methods.

Is there a pragmatical way to describe service method and its arguments in case like this? (in Java).

答:
It sounds like you're creating a library for others to use.  If it were me, I would pass in a user object partially populated with the known values, and my first step in creating a user would be to validate the input to the method.  If required fields are missing, I would throw a MissingParameter exception (that you invent) at run time.

Even if you find a way to compile-time verify the user of your library is passing in values, you still don't know that they are non-empty values.  You'll still have to throw an exception for invalid required parameters.  Hit two birds with one stone.


答:
Use compile time annotations and then use the annotation processing tools to check the mandatory parameters at compile time itself. You need 2 annotations, Mandatory and Optional.

Annotate the bean fields properly and you should be able to achieve it.

Ref Link: http://www.javalobby.org/java/forums/t17876.html

Title: Service method, bean as an argument and mandatory attributes

Body:
There is a service:

```<code>createUser(User user)
</code>```

where you can create a new user, with so many attributes (name, address lines...). Now, some user attributes are mandatory. Other attributes are not mandatory (like nickname or image).

The problem is that, from the outside, you can't tell the difference (in compile time). You can't force yourself to set only mandatory fields; moreover, the list of mandatory fields can change in the future and your code will stop working (while still compiling).

So we can

createUser(int userId, String username...) - explode the bean properties and don't use bean as an argument. Now every change will be reflected in the API, but method signatures may become huge. Also, when overloading methods for various combinations of mandatory fields with non-mandatory - that can be a mess, too.

use multiple beans, and have methods like (given names are just illustrative) createUser(UserCoreData user), createUser(UserFull user) but that still would not help much.

or have service for storing mandatory User data and then having additional services for storing additional, non-mandatory data.

(EDITED) or to split User into logical components (ie smaller beans) Address, DateFrom... and use those in service methods.

Is there a pragmatical way to describe service method and its arguments in case like this? (in Java).


答:
Make sure you have your team and your development processes solidified. I don't see how you can feel confident you're going to improve on this app with a Joel Test of 4. This project could use about 8. You could suffer the same fate this project did with uncooperative management, poor planning, inexperienced team members, lack of best practices, unexpected change requests, unreasonable time-frames. During many projects, "life happens" so you have to be prepared.

Hopefully, your company is paying to rewrite the app because it is important. Apps that are criticial usually have current bugs to fix and a large number of change requests with tight delivery schedules.  You don't like the old code because it is difficult to maintain, so you want to compound the time to fix, add new features all while you're writing a new code base? You may save time in the long-term, but you're like a business with no cash flow. How can you deliver on the changes/fixes they need right now (Joel 5 - fix bugs before new code - users will demand this)? You need some efficiencies (Joel 1,2,3,6,7 - builds, source control, schedules, specs).

Your team would be in a better position to take on this project with the right tools and environment (Joel 8 (working conditions), 9 (best tools)). Is your company ready to support this project? Can everyone outside your group commit to testing? (Joel 10, 12)

There's going to be bugs (Joel 4 & 5) in the current code and your new app
.
Programmer turn-over (Joel 11 - candidates write code during interview).

You seem to be prepared to take on this project. Make sure everyone else is. You may need to run a tighter ship than most teams.

Title: Considerations before rewriting a software component from scratch?

Body:
A piece of software is a patchwork of old and undocumented efforts. There are no comments, no documentation, and the code is hairy -- it involves Unix shell scripts that check for dummy files and then call SQL statements that call database procedures that modify data.

The original developers have left and we score a solid 2 on the Joel Test but I can raise it to at least 4 - yay...

The code is reasonably error-free, but we constantly need to add new features into it which is highly error-prone because of the state of the code, so the deadlines slip and the efforts rise.

We want to rewrite this software in order to reduce maintenance and development efforts. As part of the rewrite, we will introduce specs, comments, test cases -- all things that we currently don't have. It'll still be a bit complex afterwards, but no more than necessary.

This is not a BIG rewrite because we are not going to switch languages or frameworks; we'll still need shell scripts (but fewer) and database procedures (but fewer). The implications are also fairly simple because we're in control of the installation sites and we can fully replace the old code with the new code at the flick of a switch.

I know a rewrite is never good but I think these are reasonable counterarguments. Nevertheless, my concern is the typical danger of introducing brand new bugs instead of the old known ones, and also the danger of not implementing certain details because nobody even knows they exist or are needed.

How can I approach this rewrite in an efficient manner?


问:
Why is Web SQL database deprecated?
I am making a hybrid Android app.

At first I decided to use localStorage, after spending 2 days, I realized that it is very strange and so dropped it.

Then, I picked up indexedDB, after spending today's whole day and actually getting the output in Google Chrome, it is not running inside a WebView of the android app.

And I never used Web SQL database at all because it was deprecated. Anyhow, it has come to my notice that PhoneGap still uses Web SQL and android's browsers support it.

Why was Web SQL deprecated in the first place? And will it be a good idea for me to go with Web SQL now?

答:
Short version:  Web SQL was deprecated because standards are really important and turning Web SQL into a proper standard would have been prohibitively difficult.

Since existing implementations of Web SQL are basically wrappers around SQLite, any attempt to define a standard of it was basically "do what SQLite does."  This isn't good enough; a true standard needs to be self-contained, to define the interface and corner cases and exceptions itself instead of pointing to an existing implementation (especially a third-party implementation like SQLite).  Otherwise, you run the risk of taking one particular implementation's quirks and enshrining them as the standard.  From what I've read, the W3C prefers multiple independent implementations of proposed standards to help ensure that this happens; since Web SQL was so tied to SQLite, that just wasn't going to happen.

Mozilla's blog gives more details on their reasoning in particular for not supporting Web SQL; apparently they were one of the major voices in getting Web SQL deprecated.

Should you go with Web SQL now?  I don't expect the vendors that currently support it (like Google and Apple) to drop it any time soon, but IE and Firefox won't be adding it, and since it's deprecated, why invest in it?  (For example, Ido Green, with Google Developer Relations, doesn't recommend using it.)

Title: Why is Web SQL database deprecated?


答:
It's not that rewritten code is bad, it's how you do it.  Everyone thinks their case is the exception.

A large rewrite is like climbing a mountain.  You don't want to remove the previous safety until the next one is in place, and you take small, deliberate steps.  It feels like taking the time to do it safely is keeping you from reaching the top, but you eventually do get there.

Figure out the easiest, smallest, most beneficial part you can refactor, put tests around it, then do it, without changing the rest of the code.  Then repeat the process.  Sometimes this requires temporary hack code to bridge between the old and the new code.  Things might temporarily get worse before they get better, but you will move in the right direction in the long term.  The idea is that if you screw up any part of the rewrite, you can get back to a known good state without reverting more than a day or so of work in source control.


答:
If possible, do it module by module.

If the current system is not "very modular", try and identify pieces that can be modularised, and refactor them 1 at a time, introducing test cases etc.

Start with what appears to be the easiest module. Get it right. Then move on to the next.

You seem to have a pretty good grasp of what you should be doing though, so good luck!


问:
Either Monad and Exceptional Circumstances
I have a function returning an Either such as GetUserFromDb(int id).

If the database is offline, should I catch the error in the function and wrap it in a failure / Left case or should I let it bubble out as an exception as there is nothing I can do and it really is an exceptional situation?

答:
Really, it depends on your domain model. Why is it that you use an Either in the first place? Generally speaking, the fact that a record for a particular ID isn't found because the record doesn't exist, is a normal result but that the record isn't found because the DB doesn't exist is not. So, it certainly makes sense to treat the two cases differently, i.e. return an Either in the first case and throw an exception in the second.

Of course, in a distributed application or a mobile one, losing the DB connection might be normal. And when using the DB only as dumb storage and managing all relationships in your application, not finding a record that the app expects to be there is an exceptional situation. It all depends on context.


问:
How to show or direct a business analyst to do data modelling?
Our business analysts pushed hard to collect data through a spreadsheet.  I am the programmer responsible for importing that data.  Usually when they push hard for something like this, I never know how well it will work out until a few weeks later when I have time assigned to work on the task of programming the import of the data.  I have tried to do as much as possible along the way, named ranges, data validations, etc.  But I usually don't have time to take a detailed look at all the data and compare to the destination in the database to determine how well it matches up.

A lot of times there will be maybe a little table of items that somehow I have to relate to something else in the database, but there are not natural or business keys present that would allow me to do so.   Make the best of this, trying to write something that can compare strings and make a best guess at it and then go through the effort of creating interfaces for a user to match the imported data to the destination.

I feel like if the business analyst was actually creating a data model, they would be forced to think about these relationships, and have an appreciation for the need of natural or business keys to be part of the spreadsheet for the purposes of smoothly importing the data.  The closest they come to business analysis is a big flat list of fields, and that would be fine if it were like any other data dictionary and include data types+relationships, but it isn't.  They are just a bunch of names.  No indication of what type of data they might hold, and it is up to me to guess.  When I have pushed for more detail, they say that it is just busy work.

How can I explain the importance of data modelling?  How can I tell them what it is and how to do it?  It feels impossible, because they don't have an appreciation for its importance.  They do however, usually have an interest in helping out in whatever way they can, it's just this in particular has never gotten a motivated response.

答:
Buy the Business Analyst a cup of coffee. Start by asking them to explain to you why the they gather the data in the spreadsheets in the manner that they do.

Its just like writing code, you need to understand the problem you are trying to solve before you write the code to solve it.

A lot of developers often miss this because they feel that technical proficiency is more important than anything else (and this is coming from a developer). Explain to him or her how your approach can help them meet the objective and get the job done more efficiently.

There may be a reason for these spreadsheets that you have not considered. For example, Business Analyst are often communicating with non technical senior management persons (what the developer often doesn't see) and trust me, the essentials of data modeling means very little that audience.


问:
Is navigate between more than one class a bad practice?
I have the following class with the following function (some implementation details have been skipped):

```<code>public class TitleScreen : GameScreen
{
    public Texture2D titleScreen;

    public override void Draw (GameTime gameTime)
    {
        ScreenManager.SpriteBatch.Draw (titleScreen, new Rectangle (0, 0, ScreenManager.Game.Window.ClientBounds.Width, ScreenManager.Game.Window.ClientBounds.Height), Color.White);
    }
}
</code>```

This class is associated with a class "ScreenManager", which is associated with a Game, which is associated with a Window. As you can see, I navigate through several classes in order to obtain the bounds of the Window so I can draw it.

My question is: Is that a bad practice? Am I coupling the TitleScreen class with Game and Window? It would be better to implement a function in ScreenManager to return the Width and Height of the window?

答:
To round out my comment above:

The guiding principle involed - The Law of Demeter:

The principle in question here is the Law of Demeter, which very loosely states (taken from Wikipedia):

[Objects should] only talk to [their] immediate friends.

In this sense, your code seems to be violating a fairly important guiding principle of object orientation.  So one possible solution here would be to only talk to ScreenManager, and ask it to give you the ClientBounds.  Unfortunately, you may not be in control of the code (i.e. ScreenManager, etc), so this may be impossible.  Even if it is possible, you can see that ScreenManager cannot simply call Game.Window.ClientBounds without breaking the Law again, so it needs to ask Game to get the ClientBounds.  Depending on who you ask, this gets unmaintainable real quick.  Wikipedia's article goes on to give the following warning:

Although the LoD increases the adaptiveness of a software system, it may also result in having to write many wrapper methods to propagate calls to components; in some cases, this can add noticeable time and space overhead.

A different take on the principle - as DTOs:

Robert Martin's generally excellent book Clean Code calls the above chaining of calls a "train wreck", both for its looks, as well as the ability for something to go wrong.  However, a distinction is made (hopefully Uncle Bob doesn't mind my quoting here, with some modifications):

Are these two snippets of code violations
  of the Law of Demeter? Certainly
  the containing module knows [snip]... That’s a lot of knowledge
  for one function to know. The calling function knows how to navigate through
  a lot of different objects.  Whether this is a violation of Demeter depends on whether or not [list of objects, in your case: Game and Window] are objects or data structures. If they are objects, then their internal structure should be hidden rather than exposed, and so knowledge of their innards is a clear violation of the Law of Demeter. On the other hand, if [they] are just data structures with no behavior, then they naturally expose their internal structure, and so
  Demeter does not apply.

So, in summary, the Law of Demeter might not be violated, if we see the intermediate objects as primarily DTOs (objects with no behavior).

A possible suggestion: IoC

If you are getting to the point where this type of thing becoming a concern, you can always consider Inversion of Control.  In short, we're talking about taking out the logic of how to obtain the ClientBounds object out of the TitleScreen.  In general then, TitleScreen would expect to be provided with a ClientBounds around the time of its construction (although there are a variety of other approaches, such as property or method parameter injection); shifting the responsibility of knowing about the full object hierarchy somewhere else (typically some wiring code).

While this doesn't necessarily solve the violation of the LoD, it does give you an opportunity to remove some duplication from your project.  You also make TitleScreen less dependent on the entire object chain, and potentially more unit testable.

It's completely possible to do this by hand, but to make IoC more realistic and bearable, people normally use dependency injection frameworks, such as Unity or Ninject.


答:
What your title screen needs to know is its width and height. Where this information comes from should be none of its concern (loose coupling).

When the width and height are constant, I would pass them to the constructor.

When they might change in some well-defined circumstances, I would create a setter for these variables (currentScreen.setSize(width, height)).

When they change all the time, I would pass a reference to the ClientBounds object to it so it can check it everytime before drawing a frame.

For the rationale behind this, you might want to read about the principle of dependency injection. When an object depends on an object of another class, it shouldn't get that object itself. It should receive it from the outside. This makes your code much more modulary and flexible.

Title: Is navigate between more than one class a bad practice?

Body:
I have the following class with the following function (some implementation details have been skipped):

```<code>public class TitleScreen : GameScreen
{
    public Texture2D titleScreen;

    public override void Draw (GameTime gameTime)
    {
        ScreenManager.SpriteBatch.Draw (titleScreen, new Rectangle (0, 0, ScreenManager.Game.Window.ClientBounds.Width, ScreenManager.Game.Window.ClientBounds.Height), Color.White);
    }
}
</code>```

This class is associated with a class "ScreenManager", which is associated with a Game, which is associated with a Window. As you can see, I navigate through several classes in order to obtain the bounds of the Window so I can draw it.

My question is: Is that a bad practice? Am I coupling the TitleScreen class with Game and Window? It would be better to implement a function in ScreenManager to return the Width and Height of the window?


答:
Depending on how large of an array you are working with you may wish to apply the functional programming "decorate sort undecorate" pattern (which is a form of memoization).

Constantly splitting the string into parts getting its length and then discarding the data can be inefficient, after all, the string isn't changing while you are sorting it, you only need to do it once.

In perl, this is known as a Schwartzian transform - the code for this looks like:

#!/usr/bin/perl
use strict;
my @data = qw ( 1.34 1.15 1.1 1.2 1.26 1.10 1.20 1.17 );
my @sorted =
    map { $_->[0] }
    sort { $a->[1] <=> $b->[1] or $a->[2] <=> $b->[2]  }
    map {
      my @l = split(/\./);
      [$_, length($l[1]), $l[1]] }
    @data;
print join(',', @sorted),"\n";
```

<p>The trick to this is that the change of "1.15" to ["1.15", 2, 15] is only done once, and then the sort is working off of those values.  For small sized arrays this is a minor boost in performance.  For large arrays, it can be very significant.</p>

<p>In languages that lack the "just toss things in an array and sort it however", this becomes a bit more complex.  You would need to build an object that has the original data and the component parts and the sortable.  This is slightly easier to work with because you could put it in the constructor.</p>

<p>In Java, one could use the following approach:</p>

<pre class="lang-java prettyprint-override"><code>public class DecimalSortable implements Comparable<DecimalSortable> {
    private int len;
    private int dec;
    private String data;
    public DecimalSortable(String data) {
        this.data = data;
        String[] array = data.split("\\.");
        len = array[1].length();
        dec = Integer.parseInt(array[1]);
    }

    @Override
    public int compareTo(DecimalSortable o) {
        int rv = Integer.compare(len, o.len);
        if(rv == 0) {
            rv = Integer.compare(dec, o.dec);
        }
        return rv;
    }

    public String getData() {
        return data;
    }
}
</code>```

Note the single call to split and extraction of the values that are then later sorted on.  Yes, its a bit more overhead than the more dynamic languages, but you get the idea of how it works and how to avoid repeated calls to split (and the related creation of new String objects for each comparison).

Body:
Depending on how large of an array you are working with you may wish to apply the functional programming "decorate sort undecorate" pattern (which is a form of memoization).

Constantly splitting the string into parts getting its length and then discarding the data can be inefficient, after all, the string isn't changing while you are sorting it, you only need to do it once.

In perl, this is known as a Schwartzian transform - the code for this looks like:

#!/usr/bin/perl
use strict;
my @data = qw ( 1.34 1.15 1.1 1.2 1.26 1.10 1.20 1.17 );
my @sorted =
    map { $_->[0] }
    sort { $a->[1] <=> $b->[1] or $a->[2] <=> $b->[2]  }
    map {
      my @l = split(/\./);
      [$_, length($l[1]), $l[1]] }
    @data;
print join(',', @sorted),"\n";

The trick to this is that the change of "1.15" to ["1.15", 2, 15] is only done once, and then the sort is working off of those values.  For small sized arrays this is a minor boost in performance.  For large arrays, it can be very significant.

In languages that lack the "just toss things in an array and sort it however", this becomes a bit more complex.  You would need to build an object that has the original data and the component parts and the sortable.  This is slightly easier to work with because you could put it in the constructor.

In Java, one could use the following approach:

public class DecimalSortable implements Comparable<DecimalSortable> {
    private int len;
    private int dec;
    private String data;
    public DecimalSortable(String data) {
        this.data = data;
        String[] array = data.split("\\.");
        len = array[1].length();
        dec = Integer.parseInt(array[1]);
    }

    @Override
    public int compareTo(DecimalSortable o) {
        int rv = Integer.compare(len, o.len);
        if(rv == 0) {
            rv = Integer.compare(dec, o.dec);
        }
        return rv;
    }

    public String getData() {
        return data;
    }
}

Note the single call to split and extraction of the values that are then later sorted on.  Yes, its a bit more overhead than the more dynamic languages, but you get the idea of how it works and how to avoid repeated calls to split (and the related creation of new String objects for each comparison).


答:
Don't use a Java Bean if you can

While Java Beans are extremely useful on many occasions, I would argue that it would be better for User not to be a bean in the context you describe. You can design this class so that its instances are always in a valid state.

In the following example, name is mandatory and address is optional.

```<code>class User {
    private String name;
    private String address;

    User(String name) {
        setName(name);
    }

    void setName(String name) {
        if (name == null)
            throw new IllegalArgumentException("[name] cannot be null");
        this.name = name;
    }
    String getName() {
        return name;
    }

    void setAddress(String address) {
        this.address = address;
    }
    String getAddress() {
        return address;
    }
}
</code>```

As you can see, with that design, it is not possible at any point to have a User instance without a name. However, you can have instances with an address, as well as instances without one.

Also notice that in the code example above I am performing some basic validation. If needed, you can perform more complex validation than that. For example by making sure the name does not contain characters not likely to appear in your context.

Things to consider

There are a few things to consider to make sure such a class meets its goal. Only its immutable content can be shown to the outside world, for example. Consider another similar class that contains a list that must always contain at least one item. If that list is mutable and external code can access it (through a getter, for example), nothing stops it from removing objects from it until it is empty, putting your initial instance in a state that shouldn't be allowed. Of course, if you need to expose that data, consider only giving a copy of the list or have it immutable.

What if there are a lot of mandatory values ?

If it makes sense to group some of these values in classes of their own, and that in doing so the constructor becomes wieldable, go for it. Such classes should be designed with the aforementioned constraints in mind.

Alternatively, you can define a Builder to help in constructing the objects.

What if a Java Bean is needed in a specific part of my code?

That design may work well in most places these classes are used except at specific places where, because for example a framework needs it, you must use Java beans. When that happens, instead of using beans everywhere, you can define a bean that contains the same data with added constructor and method to take care of data conversion. For example...

```<code>class UserBean {
    private String name;
    private String address;

    UserBean() {
    }
    UserBean(User user) {
        this.name = user.getName();
        this.address = user.getAddress();
    }

    void setName(String name) {
        this.name = name;
    }
    String getName() {
        return name;
    }

    void setAddress(String address) {
        this.address = address;
    }
    String getAddress() {
        return address;
    }

    User toUser() {
        User ret = new User(name);
        ret.setAddress(address);
        return ret;
    }
}
</code>```

That way it is easy to have a bean from the non-bean instance and vice-versa.

Conclusion

As you can see the problem you have can be solved while keeping its initial signature. It is possible that going this way results in more code to be written for a similar result (though I wouldn't vouch for it, since passing a necessarily valid object around means less validation needed by the code using it).

I have tried to keep it short (ahem...) and to use here a design close to your initial one (beans). However, it is more for the sake of the explanation rather than because I consider that the best design. With all the hassle of maybe needing builders and additional bean classes, I would tend to go the extra mile and make the class being passed around immutable. That is how I have designed a recent, short project and it turned out to work particularly well.

Body:
Don't use a Java Bean if you can

While Java Beans are extremely useful on many occasions, I would argue that it would be better for User not to be a bean in the context you describe. You can design this class so that its instances are always in a valid state.

In the following example, name is mandatory and address is optional.

class User {
    private String name;
    private String address;

    User(String name) {
        setName(name);
    }

    void setName(String name) {
        if (name == null)
            throw new IllegalArgumentException("[name] cannot be null");
        this.name = name;
    }
    String getName() {
        return name;
    }

    void setAddress(String address) {
        this.address = address;
    }
    String getAddress() {
        return address;
    }
}

As you can see, with that design, it is not possible at any point to have a User instance without a name. However, you can have instances with an address, as well as instances without one.

Also notice that in the code example above I am performing some basic validation. If needed, you can perform more complex validation than that. For example by making sure the name does not contain characters not likely to appear in your context.

Things to consider

There are a few things to consider to make sure such a class meets its goal. Only its immutable content can be shown to the outside world, for example. Consider another similar class that contains a list that must always contain at least one item. If that list is mutable and external code can access it (through a getter, for example), nothing stops it from removing objects from it until it is empty, putting your initial instance in a state that shouldn't be allowed. Of course, if you need to expose that data, consider only giving a copy of the list or have it immutable.

What if there are a lot of mandatory values ?

If it makes sense to group some of these values in classes of their own, and that in doing so the constructor becomes wieldable, go for it. Such classes should be designed with the aforementioned constraints in mind.

Alternatively, you can define a Builder to help in constructing the objects.

What if a Java Bean is needed in a specific part of my code?

That design may work well in most places these classes are used except at specific places where, because for example a framework needs it, you must use Java beans. When that happens, instead of using beans everywhere, you can define a bean that contains the same data with added constructor and method to take care of data conversion. For example...

class UserBean {
    private String name;
    private String address;

    UserBean() {
    }
    UserBean(User user) {
        this.name = user.getName();
        this.address = user.getAddress();
    }

    void setName(String name) {
        this.name = name;
    }
    String getName() {
        return name;
    }

    void setAddress(String address) {
        this.address = address;
    }
    String getAddress() {
        return address;
    }

    User toUser() {
        User ret = new User(name);
        ret.setAddress(address);
        return ret;
    }
}

That way it is easy to have a bean from the non-bean instance and vice-versa.

Conclusion

As you can see the problem you have can be solved while keeping its initial signature. It is possible that going this way results in more code to be written for a similar result (though I wouldn't vouch for it, since passing a necessarily valid object around means less validation needed by the code using it).

I have tried to keep it short (ahem...) and to use here a design close to your initial one (beans). However, it is more for the sake of the explanation rather than because I consider that the best design. With all the hassle of maybe needing builders and additional bean classes, I would tend to go the extra mile and make the class being passed around immutable. That is how I have designed a recent, short project and it turned out to work particularly well.


答:
In Java the abstraction used to represent files is a stream, some streams are unidirectional (read only or write only) others are bidirectional.  For Ruby the File class is the abstraction that represents OS files.  So the question becomes what is its single responsibility?  In Java, FileWriter's responsibility is to provide a unidirectional stream of bytes that is connected to an OS file.  In Ruby, File's responsibility is to provide bidirectional access to a system file.  They both fulfill the SRP they just have different responsibilities.

It's not a Car's or a Dog's responsibility to convert itself to a string, now is it?

Sure why not?  I expect the Car class to fully represent a Car abstraction.  If it makes sense for the car abstraction to be used where a string is necessary then I fully expect the Car class to support conversion to a string.

To answer the larger question directly a class's responsibility is to act as an abstraction.  That job may be complex, but that is kind of the point, an abstraction should hide complex things behind an easier to use, less complex interface. The SRP is a design guideline so you focus on the question "what does this abstraction represent?". If multiple different behaviors are necessary to fully abstract the concept then so be it.

Title: What is the real responsibility of a class?

Body:
I keep wondering if it is legitimate to use verbs that are based on nouns in OOP.

I came across this brilliant article, though I still disagree with the point it makes.

To explain the problem a bit more, the article states that there shouldn't be, for instance, a FileWriter class, but since writing is an action it should be a method of the class File. You'll get to realize that it's often language dependent since a Ruby programmer would likely be against the use of a FileWriter class (Ruby uses method File.open to access a file), whereas a Java programmer wouldn't.

My personal (and yes, very humble) point of view is that doing so would break the Single Responsibility principle. When I programmed in PHP (because PHP is obviously the best language for OOP, right?), I would often use this kind of framework:

```<code><?php

// This is just an example that I just made on the fly, may contain errors

class User extends Record {

    protected $name;

    public function __construct($name) {
        $this->name = $name;
    }

}

class UserDataHandler extends DataHandler /* knows the pdo object */ {

    public function find($id) {
         $query = $this->db->prepare('SELECT ' . $this->getFields . ' FROM users WHERE id = :id');
         $query->bindParam(':id', $id, PDO::PARAM_INT);
         $query->setFetchMode( PDO::FETCH_CLASS, 'user');
         $query->execute();
         return $query->fetch( PDO::FETCH_CLASS );
    }

}

?>
</code>```

It is my understanding that the suffix DataHandler doesn't add anything relevant; but the point is that the single responsibility principle dictates us that an object used as a model containing data (may it be called a Record) shouldn't also have the responsibility of doing SQL queries and DataBase access. This somehow invalidates the ActionRecord pattern used for instance by Ruby on Rails.

I came across this C# code (yay, fourth object language used in this post) just the other day:

```<code>byte[] bytes = Encoding.Default.GetBytes(myString);
myString = Encoding.UTF8.GetString(bytes);
</code>```

And I gotta say that it doesn't make much sense to me that an Encoding or Charset class actually encodes strings. It should merely be a representation of what an encoding really is.

Thus, I would tend to think that:

It is not a File class responsibility to open, read or save files.

It is not a Xml class responsibility to serialize itself.

It is not a User class responsibility to query a database.

etc.

However, if we extrapolate these ideas, why would Object have a toString class? It's not a Car's or a Dog's responsibility to convert itself to a string, now is it?

I understand that from a pragmatic point of view, getting rid of the toString method for the beauty of following a strict SOLID form, that makes code more maintainable by making it useless, is not an acceptable option.

I also understand that there may not be an exact answer (which would more be an essay than a serious answer) to this, or that it may be opinion-based. Nevertheless I would still like to know if my approach actually follows what the single-responsibility principle really is.

What's a class's responsibility?


问:
How are algorithms developed?
I'm impressed with the efficiency of some algorithms and I noticed the way the problem is solved can be and/or appear really unintuitive.

It may sound dumb, but I would like to know:

How do the authors come up with amazing algorithms? Do they just keep thinking about the problem and end up with the answer? Are they geniuses?

Which leads me to my next question: how long do they take to find the solution? Hours, days, months, years?

I know there isn't a definite answer to these questions. But I would like to know how it usually works regarding the most used/known algorithms.

答:
How are algorithms developed?

Generally, here's how algorithms are developed.

Find a problem (or a problem with an existing solution)

Find a solution to the problem

Repeat steps 1 & 2 until you either can't find a problem or you can't fix it.

The resulting solution is the algorithm to resolve the problem.

"Really Useful" algorithms come about when you have an existing single-purpose algorithm and realize that it could be used in a different context with a few modifications.  That realization is what re-triggers the iterative cycle.

This is where a lot of the generalization behind an algorithm comes from.  And, as Robert Harvey stated, this extended iterative cycle is where software patterns come from.

It's equivalent to saying "I solved foo with this, and if I tweak that solution a bit then I could solve bar as well."  And then that potentially extends into solving baz and so on as well.  Solve enough challenges with the approach and it becomes generalizable as an algorithm or a pattern.

How long does that take?

It all depends upon the nature of the problem, the available solutions, and the tooling used to tackle the problem.

To help clarify Step #2 in the general approach:  This is where a lot of the hard work and inspiration goes into creating an algorithm.  Your first attempts at solving the problem will likely either fail or won't be all that elegant.

But you start with "well, how would I break that problem apart and solve it?" Remember that an algorithm is a step-by-step approach to solving a problem.  So you break the problem down into steps and see how well that approach solves the problem.  Also keep in mind that Problem Solving is a broad field of research.  Some methods are more successful than others, and sometimes it's the unorthodox approach that develops the elegant solution.

Title: How are algorithms developed?


答:
Algorithm development is a fundamental problem and as such, it is a popular topic in the research community.

Very specialized people with strong backgrounds in mathematic are working to solve new problems or improve old ones. Beside, good algorithm can be a significant advantage for some software compagnies, and you don't need a lot of money to experiment in this field.

So you have an army of bright people publishing papers hoping to become famous and using everything others are discovering, and easy to use almost free working environments to perform  all the tests they need.

For each solution/improvement published, there will be a number of people asking themselves:

can I do better than this?

how can I use this to solve my other problems?

This process runs for years, and involves a lot of people (even if they are not directly interacting)

Title: How are algorithms developed?

Body:
I'm impressed with the efficiency of some algorithms and I noticed the way the problem is solved can be and/or appear really unintuitive.

It may sound dumb, but I would like to know:

How do the authors come up with amazing algorithms? Do they just keep thinking about the problem and end up with the answer? Are they geniuses?

Which leads me to my next question: how long do they take to find the solution? Hours, days, months, years?

I know there isn't a definite answer to these questions. But I would like to know how it usually works regarding the most used/known algorithms.


答:
Creating something new and better usually requires a flash of insight that can't really be taught or explained, but there are things you can do to help it along:

Understand the work of others.  Start with college courses or textbooks on algorithms.  Look for papers, blogs, Stack Exchange answers, or open source code for similar problems.

Determine the theoretical best asymptotic complexity.  When you exceed that complexity, you'll know there is room for improvement.

Whiteboard it.  Draw diagrams, lists, and issues.  Think about how a human would solve the problem manually.  Don't just jump into coding.

Experiment. Try different data structures.  Try working in reverse from the obvious answer.  Try preprocessing some data to make it quicker to work with.  Try breaking the problem down into simpler steps.  Try different techniques from existing algorithms.

Continuous refinement.  27-year world chess champion Emanuel Lasker said, "When you see a good move wait—look for a better one."  Find the parts you don't like about your algorithm and make it better.

Title: How are algorithms developed?


答:
Many times you can adapt existing algorithms or piece together other algorithms.

Quick sort for example where someone realized they could subdivide a problem into smaller sets and utilize sorting methods that are more efficient with small sets.  However, it just utilizes pre-existing algorithms for the sorting of elements.

Using quad trees to index geographical, pieces together pre-existing algorithms data structures, but applies them to a new problem.

So while some algorithms are truly innovative, alot of "innovation" is nothing more than someone realizing an existing tool fits a certain problem well.  So if you want to develop algorithms, you should have familiarity with other existing algorithms.

Title: How are algorithms developed?


答:
I also understand that there may not be an exact answer (which would more be an essay than a serious answer) to this, or that it may be opinion-based. Nevertheless I would still like to know if my approach actually follows what the single-responsibility principle really is.

While it does, it might not necessarily make for good code. Beyond the simple fact that any sort of blindly followed rule leads to bad code, you're starting off an invalid premise: (programming) objects are not (physical) objects.

Objects are a set of cohesive bundles of data and operations (and sometimes only one of the two). While these often model real world objects, the difference between a computer model of something and that thing itself necessitates differences.

By taking that hard line between a "noun" that represents a thing and other things that consume them, you're going against a key benefit of object oriented programming (having function and state together so that the function can protect invariants of the state). Worse, you're trying to represent the physical world in code, which as history has shown, will not work well.


问:
Should I use one database per application or share a single database amongst multiple applications
I have multiple applications some that use data from the same sources.
Is it best practice (or what are the pros/cons) to:

leave the data in databases shared by multiple applications

saves space as only one database is needed

complicates indexing as different applications have different querying needs

import data daily into per-app databases

uses more space as duplicated data exists in per-app databases

easier indexing as each app can focus on its individual needs

I may have left out other advantages/disadvantages, please list if any, also how is this done at your workplace?

答:
Once I had multiple websites which got popular over time. They used separate databases, mostly because the hosting provider allowed only 1Gb storage space each. But! As soon as I released a service that included all these websites, I started having to do transactions amongst these websites, and the most convenient way to do this is definately moving everything into one big database.

So I optimized the database structure and squeezed the relevant parts to this central database, but left everything else out.

My opinion is somehow related to the paradigms of OOP. Similar data must be stored together, so if you build different applications, you should use different databases for them.

In the above case using common db couldn't be avoided, but remember that I also kept some tables apart in a separate db, that aren't part of the common queries.

Moreover, if you keep them separated, they will be easier to backup, there will be less chance for data loss. If something goes wrong and applications interfere with each other, the database gets messed up, and you basically don't want to expose your app to this danger.

All in all, you can maintain a common database for common queries, but also keep one for each of your applications.


答:
Given some divergences between languages, this can be a tricky topic. Thus, I'm formulating the following commentaries in a way that tries to be as comprehensive as I can inside the realm of OO.

First of all, the so called "Single Responsibility Principle" is a reflex -- explicitly declared -- of the concept cohesion. Reading the literature of the time (around '70), people were (and still are) struggling to define what a module is, and how to construct them in a way that would preserve nice properties. So, they would say "here is a bunch of structures and procedures, I'll make a module out of them", but with no criteria as to why this set of arbitrary things are packaged together, the organization might end up making little sense -- little "cohesion". Hence, discussions on criteria emerged.

So, the first thing to note here is that, so far, the debate is around organization and related effects on maintenance and understandability (for little matter to a computer if a module "makes sense").

Then, someone else (mr. Martin) came in and applied the same thinking to the unit of a class as a criteria to use when thinking about what should or should not belong to it, promoting this criteria to a principle, the one being discussed here. The point he made was that "A class should have only one reason to change".

Well, we know from experience that many objects (and many classes) that appear to do "many things" have a very good reason for doing so. The undesirable case would be the classes that are bloated with functionality to the point of being impenetrable to maintenance, etc. And to understand the latter is to see where mr. Martin was aiming at when he elaborated on the subject.

Of course, after reading what mr. Martin wrote, it should be clear these are criteria for direction and design to avoid problematic scenarios, not in any way to pursue any kind of compliance, let alone strong compliance, specially when "responsibility" is ill defined (and questions like "does this violates the principle?" are perfect examples of the widespread confusion). Thus, I find it unfortunate it is called a principle, misleading people into try to take it to the last consequences, where it would do no good.  Mr. Martin himself discussed designs that "do more than one thing" that should probably be kept that way, since separating would yield worse results. Also, there are many known challenges regarding modularity (and this subject is a case of it), we are not at a point of having good answers even for some simple questions about it.

However, if we extrapolate these ideas, why would Object have a toString class? It's not a Car's or a Dog's responsibility to convert itself to a string, now is it?

Now, let me pause to say something here about toString: there is a fundamental thing commonly neglected when one makes that transition of thought from modules to classes and reflect on what methods should belong to a class. And the thing is  dynamic dispatch (aka, late binding, "polymorphism").

In a world with no "overriding methods", choosing between "obj.toString()" or "toString(obj)" is a matter of syntax preference alone. However, in a world where programmers can change the behavior of a program by adding a subclass with distinct implementation of an existing/overridden method, this choice is no more of taste: making a procedure a method also can make it a candidate for overriding, and the same might not be true for "free procedures" (languages that support multi-methods have a way out of this dichotomy). Consequently, it is no more a discussion on organization only, but on semantics as well. Finally, to which class the method is bound, also becomes an impacting decision (and in many cases, so far, we have little more than guidelines to help us decide where things belong, as non-obvious trade-offs emerge from different choices).

Finally, we are faced with languages that carry terrible design decisions, for instance, forcing one to create a class for every little bit of thing. Thus, what once was the canonical reason and main criteria for having objects (and in the class-land, therefore, classes) at all, which is, to have these "objects" that are kind of "behaviors that also behave like data", but protect their concrete representation (if any) from direct manipulation at all costs (and that's the main hint for what should be the interface of an object, from the point of view of its clients), gets blurred and confused.


问:
Mobile compatible JEE application
Does using frameworks like AngularJS/Backbone JS/Bootstrap/Foundation etc. automatically make the web application mobile device compatible?

Is there a framework/design approach to make applications (new or existing) mobile compatible?

To put it simply; is there a framework/guideline/library which I can use in my JEE web application UI layer making it automatically compatible both on computer browsers and mobile devices (iOS phone, iPad, Android phones and the whole array of it).

答:
"Compatible" might mean many different things. In general mobile devices run fairly modern browsers which can easily render HTML5 content and JavaScript driven web apps. You have named a number of different frameworks with different responsibilities. All of them support building mobile-friendly sites but none of them can free you from needing to think about your site's mobile experience.

If your site does not rely on Flash, Silverlight, or other plugins you probably have a working mobile site however there are additional design and implementation concerns you should probably consider.

Most mobile devices do not provide a mouse pointer so sites which depend on mouse-over or hover interactions can be unusable.

Does your site work well on high latency, low bandwidth network connections? Are you serving large images to mobile devices? Can your web servers handle a large number of long-lived slow requests?

Does your site server reasonable markup to enable user interactions? For example HTML5 input elements with input types will allow mobile devices to present an appropriate keyboard (email, numeric) or other interface (date pickers and so on).

Finally does your site's design work on small screens and viewports? The phrase you're probably looking for here is "responsive design". Both Bootstrap and Foundation provide support for flexible grids which can scale as percentages of the available viewport or be adjusted using media queries to jump between several specific layouts depending on the rendering device's viewport size.

Title: Mobile compatible JEE application


问:
Cookie access within a HTTP Class
I have a HTTP class that has a Get, and Post, method. It's a simple class I created to encapsulate Post and Get requests so I don't have to repeat the get/post code throughout the application.

In C#:

```<code>class HTTP
{
    private CookieContainer cookieJar;
    private String userAgent = "...";

    public HTTP()
    {
        this.cookieJar = new CookieContainer();
    }

    public String get(String url)
    {
        // Make get request. Return the JSON
    }

    public String post(String url, String postData)
    {
        // Make post request. Return the JSON
    }
}
</code>```

I've made the CookieJar a property because I want to preserve the cookie values throughout the session. If the user is logged into Twitter with my application, each request I make (be it get or post) I want to use the cookies so they remain logged in.

That's the basics of it anyway. But, I don't want to return a string in all instances. Sometimes I may want the cookie, or a header value, or something else from the request.

Ideally I'd like to be able to do this in my code:

```<code>Cookie cookie = http.get("http://google.com").cookie("g_user");
String g_user = cookie.value;
</code>```

or

```<code>String source = http.get("http://google.com").body;
</code>```

My question - To do this, would I need to have a Get class, and a Post class, that are included within the HTTP class and are accessible via accessors?

Within the Get and Post class I would then have the Cookie method, and the body property, and whatever else is needed.

Should I also use an interface, or create a Request class and have Post and Get extend it so that common methods and properties are available to both classes?

Or, am I thinking totally wrong?

答:
For C#, can you use System.Net.HttpWebRequest? That class also seems to support cookies in HTTP requests, thought they appear to be turned off by default (you can turn them on), as noted here:

For security reasons, cookies are disabled by default. If you want to
  use cookies, use the CookieContainer property to enable cookies.

If you are trying to build your own class for learning purposes, then that class might still serve as a valuable reference point.

Title: Cookie access within a HTTP Class


问:
How necessary is it to follow defensive programming practices for code that will never be made publicly available?
I'm writing a Java implementation of a card game, so I created a special type of Collection I'm calling a Zone. All modification methods of Java's Collection are unsupported, but there's a method in the Zone API, move(Zone, Card), which moves a Card from the given Zone to itself (accomplished by package-private techniques).  This way, I can ensure that no cards are taken out of a zone and simply vanish; they can only be moved to another zone.

My question is, how necessary is this kind of defensive coding? It's "correct," and it feels like the right practice, but it's not like the Zone API is ever going to be part of some public library. It's just for me, so it's kind of like I'm protecting my code from myself when I could probably be more efficient by just using standard Collections.

How far should I take this Zone idea? Can anyone give me some advice on how much I should think about preserving the contracts in classes I write, especially for ones that aren't really going to be publicly available?

答:
First create a class that keeps a list of Zones so you don't lose a Zone or the cards in it.  You can then check that a transfer is within your ZoneList.  This class will probably be a sort of singleton, as you'll only need one instance, but you might want sets of Zones later, so keep your options open.

Second, don't have Zone or ZoneList implement Collection or anything else unless you expect to need it.  That is, if a Zone or ZoneList will be passed to something that expects a Collection, then implement it.  You can disable a bunch of methods by having them throw an exception (UnimplementedException, or something like that) or by having them simply do nothing.  (Think real hard before using the second option.  If you do it because it's easy you'll find you're missing bugs you could have caught early on.)

There are real questions about what is "correct".  But once you figure out what it is you'll want to do things that way.  In two years you'll have forgotten about all this, and if you try to use the code then you'll get real annoyed at the guy who wrote it in such a counterintuitive manner and didn't explain anything.


答:
I usually follow some simple rules:

Try to always program by contract.

If a method is publicly available or receives input from the outside world, enforce some defensive measures (e.g. IllegalArgumentException).

For everything else that is only accessible internally, use assertions (e.g. assert input != null).

If a client is really into it, they will always find a way to make your code misbehave. They can always do it through reflection, at least.
But that's the beauty of design by contract. You don't approve such use of your code, and so you can't guarantee that it will function in such scenarios.

As to your specific case, if Zone isn't supposed to be used and/or accessed by outsiders, either make the class package-private (and possibly final), or preferably, use the collections Java already provides you. They're tested, and you don't have to reinvent the wheel. Notice that this doesn't prevent you from using assertions throughout your code to make sure everything works as expected.

Title: How necessary is it to follow defensive programming practices for code that will never be made publicly available?

Body:
I'm writing a Java implementation of a card game, so I created a special type of Collection I'm calling a Zone. All modification methods of Java's Collection are unsupported, but there's a method in the Zone API, move(Zone, Card), which moves a Card from the given Zone to itself (accomplished by package-private techniques).  This way, I can ensure that no cards are taken out of a zone and simply vanish; they can only be moved to another zone.

My question is, how necessary is this kind of defensive coding? It's "correct," and it feels like the right practice, but it's not like the Zone API is ever going to be part of some public library. It's just for me, so it's kind of like I'm protecting my code from myself when I could probably be more efficient by just using standard Collections.

How far should I take this Zone idea? Can anyone give me some advice on how much I should think about preserving the contracts in classes I write, especially for ones that aren't really going to be publicly available?


答:
I'm not going to address the design problem - just the question of whether to do things "correctly" in a non-public API.

it's just for me, so it's kind of like I'm protecting my own code from myself

That's exactly the point. Maybe there's coders out there who remember the nuances of every class and method they ever wrote and never mistakenly call into them with the wrong contract. I'm not one of them. I often forget how code I wrote is supposed to work within hours of writing it. After you think you've gotten it right once, your mind will tend to switch gears to the problem you're working on now.

You have tools to combat that. These tools include (in no particular order) conventions, unit tests and other automated tests, precondition checking, and documentation. I myself have found unit tests to be invaluable because they both force you to think about how your contract will be used and provide documentation later on how the interface was designed.