问:
Creating REST-ful web-services without adhering to the REST principles
I have built an application which acts as an interface between an EAI layer and third party vendor applications. I am using REST-ful web services for this, making use of JAX-RS API and Jersey framework. Although the web services can do different operations like Cancel, View, Create, Reschedule orders, I have implemented all of them as POST methods. But for the web-services to be REST-ful, we need to use the HTTP methods GET, POST, PUT and DELETE appropriately.

Here there are no users who can view the url to be used and hence no 'User Experience' involved. It is just a url configured at the EAI layer, which gets the request from the UI\Order Management screens. In this scenario, do we really need to make the web-services REST-ful? Whatever I have created, can they be called REST-ful web-services?

答:
I would say that it is just a Web Service not a RESTful one. It is not just a question of being stateless, but also representative of what is being done.

I've found that this article is an interesting one to read:
http://www.ibm.com/developerworks/webservices/library/ws-restful/

And no, it is not a question of user experience, it is a question of developer experience and API. As long as you use a standard framework/method another developer can pick up what is left and continue from there. Since you are talking about integration I'd say that it probably would be an excelent idea to make your services RESTful, and have a logical way of handling your WSs.

Then again, I do not have the full context of your project and this is mostly an architecture decision that most be taken considering not only the current use but also the future use and further developements.

But let me stress this once more, it is a third party integration and when doing integrations you should make it as standard as possible


问:
How to use mock objects [C++] without passing them as arguments to functions
I'm in the process of integrating a Unit Testing Framework for an existing code base in C++. I've zeroed down on CxxTest, but as it turns out we can use other Mocking Frameworks (like googlemock) in conjunction with CxxTest too.

After reading tutorials on CxxTest (Mocking) and googlemock (the infamous turtle example), I have the general idea that you have to define a mock class (using macros etc), declare an object of the mock class and then pass it to the function you are unit testing. Now, there are many occurences in the existing code base where it isn't possible to do that.

Here's an pseudo example to clarify:

```<code>class CCandidateForTest
{
    public:
    bool foo(int a)
    {
        CAnotherClass obj;
        int b = obj.bar(a+2);
        if (a == b) {
            return true;
        } else {
            return false;
        }
    }
}
</code>```

(This is over-simplified, there are also exceptions and the primitive types may also be other objects etc.; but you get the general idea) (also, creation of objects is not always direct and may sometimes use a factory)

I want to write a test for the function CCandidateForTest::foo. This method internally creates an object of CAnotherClass, which I need to mock so that CAnotherClass::bar returns different values so that different code paths in foo are traversed in unit testing.

In a nutshell, the problem is that the function being tested internally creates an object of the class that needs to be mocked - hence passing an instance of the mocked object to the function is not possible.

How do I use mocking in such a case? Is there a specific mocking framework that makes this possible?

答: Use a factory. Have the candidate class take in the factory in the constructor. Mock the factory for your test. You can use a mock lib for that or simply use separate prod and test impls of an pure abstract factory class.</p>

ContentLicense: CC BY-SA 3.0


问:
What popular "best practices" are not always best, and why?
"Best practices" are everywhere in our industry.  A Google search on "coding best practices" turns up nearly 1.5 million results.  The idea seems to bring comfort to many; just follow the instructions, and everything will turn out fine.

When I read about a best practice - for example, I just read through several in Clean Code recently - I get nervous.  Does this mean that I should always use this practice?  Are there conditions attached?  Are there situations where it might not be a good practice?  How can I know for sure until I've learned more about the problem?

Several of the practices mentioned in Clean Code did not sit right with me, but I'm honestly not sure if that's because they're potentially bad, or if that's just my personal bias talking.  I do know that many prominent people in the tech industry seem to think that there are no best practices, so at least my nagging doubts place me in good company.

The number of best practices I've read about are simply too numerous to list here or ask individual questions about, so I would like to phrase this as a general question:

Which coding practices that are popularly labeled as "best practices" can be sub-optimal or even harmful under certain circumstances?  What are those circumstances and why do they make the practice a poor one?

I would prefer to hear about specific examples and experiences.

答:
My teacher demands I start all my identifiers (not including constants) with lowercase letters, e.g. myVariable.

I know it seems like a minor thing, but many programming languages require variables to start with uppercase letters.  I value consistency, so it's a habit of mine to start everything with uppercase letters.

ContentLicense: CC BY-SA 2.5


问:
Help with complex MVVM (multiple views)
I need help creating view models for the following scenario:

Deep, hierarchical data

Multiple views for the same set of data

Each view is a single, dynamically-changing view, based on the active selection

Depending on the value of a property, display different types of tabs in a tab control

My questions:

Should I create a view-model representation for each view (VM1, VM2, etc)?

```<code>1. Yes:
    a. Should I model the entire hierarchical relationship? (ie, SubVM1, HouseVM1, RoomVM1)
    b. How do I keep all hierarchies in sync? (e.g, adding/removing nodes)

2. No:
    a. Do I use a huge, single view model that caters for all views?
</code>```

Here's an example of a single view

Figure 1: Multiple views updated based on active room. Notice Tab control

Figure 2: Different active room. Multiple views updated. Tab control items changed based on object's property.

Figure 3: Different selection type. Entire view changes

答:
Looking at your mockups, I would definitely recommend creating hierarchy of ViewModels and lots of small Views. And you will most probably have to model quite a bit of the original hierarchy.

To keep things in sync between ViewModels, use either events, or have properties to each other between ViewModels. Sync between Views and ViewModels should be standard notifying properties.

Title: Help with complex MVVM (multiple views)


问:
Debugging checklists: How much it's necessary to have?
Should making debug-checklists be an essential part of development process? How it can be integrated with unit-tests?

Update

Debugging checklist: Think about it as your troubleshooting checklist -- like what you do for your network connection, this time for your developers and your source code. For example if you're trying to access web via your web browser and you can't, then you'd probably go and check if you can load other websites or not, if not, then you'd check your internet/network connection, and so on.

Here if you have a team of multiple developers and you ran into a bug, you wouldn't just jump into the source code and try to debug it there, because someone else might changed the code and that might cause the problem. To spot the actual bug without a checklist, everybody needs to spend a lot of time looking at different things, probably in an unorganized way also.

For example we have a Map module in our software. If you're trying to use that module somewhere in the application and that doesn't work, then there is a small checklist to help you debug it faster:

Check if the license exists in Dashboard/Settings/Map or in the database. Is that a valid license?

What is the MapCenter? Is that a valid LatLng?

What is the MapProjection?

Can you reach the MapServer?

So, specially if you're new to the team/code, you can catch up with others much faster without spending hours trying to spot the cause of errors.

There are ways to do a better error handling -- like throw an exception for example if the MapServer is unreachable, however there are also situations that you still need to check different elements to make sure what exactly causing the error.

The question is: If I'm writing a sort function, and I know that you need to specify the correct encoding in order to get the correct result, should I write a checklist simply like this:

Make sure you have set the proper encoding in configuration file.

If the above example could save myself or another developer 10-15 minutes of looking around to find the problem, should we make it mandatory for every developer to write this kind of checklists when they spot something that's potential to be source of a problem on a specific part of application later?

答:
I can see two aspects to this.

With most functions there is a kind of contract that has to be fulfilled by the caller. This should be described in the documentation. This documentation can take on many different forms. It's very common to find comments in the source code explaining the purpose of the function and the parameters and return values. You can get software that extracts these comments and generates a hyperlinked help file if you want.

If you can't get the Map module (from your example) to work, you'd start by looking at this documentation to see if you are using it properly.

There's nothing wrong with writing a FAQ or trouble-shooting list for particular libraries, but this should be only if needed. The trouble with having a policy that every library must have such a list is that some simply don't need it and you spend effort to produce something of no value. What business would intentionally throw money away?

By the way, checks 2 and 3 in your Map example would be covered by the function documentation. Anyone who doesn't think of check 4 probably shouldn't be working in software development in the first place. Check 1 is valid if it isn't obvious a licence is needed, and the error message from the module is useless. (But as Julia says in her answer, it's much better to make the error message more informative than to create a troubleshooting FAQ.)

I don't see any obvious way for unit testing to include checking for required documentation. This should be part of the code review, not unit testing.


答:
There are ways to do a better error handling -- like throw an
  exception for example if the MapServer is unreachable, however there
  are also situations that you still need to check different elements to
  make sure what exactly causing the error.

True, but as a matter of course every time you need to delve in to find what's going wrong, you should add some code to provide an informative message by whatever means, in preference to adding the problem to a list. It makes very little sense to have to repeatedly check the same set of possible error causes, particularly as that list is likely to grow, when you can get your application to diagnose problems itself.

Title: Debugging checklists: How much it's necessary to have?

Body:
Should making debug-checklists be an essential part of development process? How it can be integrated with unit-tests?

Update

Debugging checklist: Think about it as your troubleshooting checklist -- like what you do for your network connection, this time for your developers and your source code. For example if you're trying to access web via your web browser and you can't, then you'd probably go and check if you can load other websites or not, if not, then you'd check your internet/network connection, and so on.

Here if you have a team of multiple developers and you ran into a bug, you wouldn't just jump into the source code and try to debug it there, because someone else might changed the code and that might cause the problem. To spot the actual bug without a checklist, everybody needs to spend a lot of time looking at different things, probably in an unorganized way also.

For example we have a Map module in our software. If you're trying to use that module somewhere in the application and that doesn't work, then there is a small checklist to help you debug it faster:

Check if the license exists in Dashboard/Settings/Map or in the database. Is that a valid license?

What is the MapCenter? Is that a valid LatLng?

What is the MapProjection?

Can you reach the MapServer?

So, specially if you're new to the team/code, you can catch up with others much faster without spending hours trying to spot the cause of errors.

There are ways to do a better error handling -- like throw an exception for example if the MapServer is unreachable, however there are also situations that you still need to check different elements to make sure what exactly causing the error.

The question is: If I'm writing a sort function, and I know that you need to specify the correct encoding in order to get the correct result, should I write a checklist simply like this:

Make sure you have set the proper encoding in configuration file.

If the above example could save myself or another developer 10-15 minutes of looking around to find the problem, should we make it mandatory for every developer to write this kind of checklists when they spot something that's potential to be source of a problem on a specific part of application later?


答:
It's a good idea, but the trick becomes where to put the checklist so troubleshooters are guaranteed to know about it and use it.  For example, we follow an agile development process at work.  That means we sometimes release features to testing that work, but aren't the full-featured user-friendly version we are ultimately working towards.

We invite everyone who will use the new feature to our demo.  We present a troubleshooting checklist, we talk about the limitations, we answer their questions, we make the list available to everyone.  Then a few days later when they actually start testing, we get a bunch of phone calls and emails and bug reports about stuff we put on the list.

As Julia pointed out, checklists in code comments or a documentation file somewhere aren't particularly helpful.  That troubleshooting information needs to be baked into the code as much as possible. If the license is invalid, you at least need a big error message saying your license is invalid, and it's better if it says go here to purchase a valid license.  If your map center is an invalid latitude/longitude, you at least need a big error message saying invalid latitude/longitude for map center, but it's better if you state what values are valid, like please specify a map center within the boundaries of Georgia.

In other words, it's your job to enable troubleshooting of your application without using a checklist.


答:
When I summarize your question as:

Should I blindly follow a design approach even though it doesn't provide me any benefit? My only justification is an anticipated, future event that may not ever occur or be an issue.

The answer becomes startling clear -

No.

One of REST's values is in making services easier to consume through a standardized approach.  You state that you don't have a need for that.  So don't worry about forcing your system into a particular design that doesn't work for you.

If you're worried about maintaining the system and available talent for future developers, just advertise your system as what it is - a collection of services.

Title: Creating REST-ful web-services without adhering to the REST principles

Body:
I have built an application which acts as an interface between an EAI layer and third party vendor applications. I am using REST-ful web services for this, making use of JAX-RS API and Jersey framework. Although the web services can do different operations like Cancel, View, Create, Reschedule orders, I have implemented all of them as POST methods. But for the web-services to be REST-ful, we need to use the HTTP methods GET, POST, PUT and DELETE appropriately.

Here there are no users who can view the url to be used and hence no 'User Experience' involved. It is just a url configured at the EAI layer, which gets the request from the UI\Order Management screens. In this scenario, do we really need to make the web-services REST-ful? Whatever I have created, can they be called REST-ful web-services?


问:
How to avoid duplication of code related to shared entities in the repository pattern?
I'm building a repository for a large CRM schema that has a high number of relations between entities.

Some of the entities are referenced by almost all entities, e.g. Person and Company.

Where I have an aggregate root such as Order, that addresses Order Header, Order Lines etc. In the case where the Order is from a new Customer, I need to insert a Company and a Person record at the same time... so far so good.

The difficulty is that this is the situation with very many other aggregate roots.

I don't want to have a private method insertPerson(IPerson) in every single repository implementation.

I have a Customer repository that already has public InsertCustomer(ICustomer) method, which persists a Company and a person record. But my reading indicates that repositories shouldn't depend on each other.

If this is a case where it is okay for repositories to depend on each other, what is the best way to go about it? Should I inject the Customer Repository into the Order repository constuctor, pass it as a parameter to the methods that need it, or never commit this evil and duplicate the identical code in all repositories, in case those repositories need to specialise that code for their specific contexts?

答: Composition and the Facade pattern.  I would split your repository into two parts: the public interface, and the actual implementation.  That way you can implement it however it makes sense for the DB, and still present a nice API to the repository's consumer.  Composition gets you the ability to reuse your customer repository implementation in the other repositories that need access to customer data.  For Specialization I would have the customer repository implement multiple interfaces to make special case access explicit and minimal, or if the changes are more in depth go with composition again (or inheritance depending on what you need) to reuse the base implementation and provide the extra functionality.</p>


问:
Syntactic Sugar for old languages
I first learned about the existence of syntactic sugar languages, like CoffeeScript and SASS while working in Rails. This got me thinking... why do we not have well-known (if any at all) syntactic sugar for languages like C, C++ and Java?

Imagine a language that reads like Python or Ruby that can be preprocessed to C, and then compiled to generate really fast code that also looks beautiful.

For example, instead of:

```<code>#include <stdio.h>

int divide(int a, int b)
{
    if(b != 0)
        return a / b;

    return 0;
}

int main()
{
    int a, b;

    scanf("%d", &a);
    scanf("%d", &b);

    printf("%d", divide(a, b));

    return 0;
}
</code>```

Why not have:

```<code>include stdio.h

fn divide(int a, int b):
  a/b if b != 0
  ret 0

fn main:
  int a, b

  scanf '%d', a
  scanf '%d', b

  print '%d', divide(a,b)
  ret 0
</code>```

And have this preprocess down to the same C code above?

Why stick to language implementations that are either fast or easy to read when you could have both?

答:
You mean things like Vala? https://wiki.gnome.org/Projects/Vala

Also note that the original C++ (C with Classes) was written purely with the C Pre-processor.

If you want to write something similarly with Python, knock yourself out.

Title: Syntactic Sugar for old languages


答:
There are two well known syntactic sugar languages for C:

C++

Objective C

And two less well known, but more truly syntactic sugar as they are set on always compiling to C while the above switched to direct assembly generation:

GObject Builder

Vala

Both C++ and Objective C started as translators to C. They switched to direct assembly generation because the code generation was getting complicated for some features. They were never designed to generate interfaces easily callable from C, but both embed complete C.

The other 2, GOB and Vala on the other hand are designed to generate interfaces easily callable from C. GOB only provides generating some boilerplate for object oriented programming while the function bodies are written in plain C, Vala is completely different language that maps to C.

All those languages provide features, not just simply different syntax. Because frankly, providing just different syntax has absolutely no benefit. It is not the syntax that governs how complicated it is to write anything in a language. It is the structural complexity of expressions and the amount of things the programmer has to keep track of. Saving a few keystrokes won't help. Programmers can generally type quite a bit faster than they think. So a different language can only help by:

Saving a lot of keystrokes. This is the case of GObject Builder and in part Vala. This is because boilerplate needed to create a GObject is rather large.

Providing actual features, like automatic reference counting in Vala.

Even then, of the four above mentioned languages, only C++ became universally popular and only because it added really powerful features. Objective C is only used on single platform and GOB and Vala are mainly niche languages for the Gnome project.

Because it is a lot of work to learn a new language. It's not enough if a programmer knows a language. Most projects are work of large teams these days and all members of the team have to know the language to use it on a project. And because people leave jobs, project leaders hesitate to use new language not only until they have enough programmers proficient in it, but also until they are sure they can hire more if needed. So new languages only catch up if they have really important new features. (Java while being rather weak language in itself has a huge advantage in comprehensive standard library. For productivity the standard library is even more important than features of the language, not to mention syntax).

Title: Syntactic Sugar for old languages

Body:
I first learned about the existence of syntactic sugar languages, like CoffeeScript and SASS while working in Rails. This got me thinking... why do we not have well-known (if any at all) syntactic sugar for languages like C, C++ and Java?

Imagine a language that reads like Python or Ruby that can be preprocessed to C, and then compiled to generate really fast code that also looks beautiful.

For example, instead of:

```<code>#include <stdio.h>

int divide(int a, int b)
{
    if(b != 0)
        return a / b;

    return 0;
}

int main()
{
    int a, b;

    scanf("%d", &a);
    scanf("%d", &b);

    printf("%d", divide(a, b));

    return 0;
}
</code>```

Why not have:

```<code>include stdio.h

fn divide(int a, int b):
  a/b if b != 0
  ret 0

fn main:
  int a, b

  scanf '%d', a
  scanf '%d', b

  print '%d', divide(a,b)
  ret 0
</code>```

And have this preprocess down to the same C code above?

Why stick to language implementations that are either fast or easy to read when you could have both?


问:
Worst coding standard you've ever had to follow?
Have you ever had to work to coding standards that:

Greatly decreased your productivity?

Were originally included for good reasons but were kept long after the original concern became irrelevant?

Were in a list so long that it was impossible to remember them all?

Made you think the author was just trying to leave their mark rather than encouraging good coding practice?

You had no idea why they were included?

If so, what is your least favorite rule and why?

Some examples here

答: At one company we had to write technical documenation that explained how we will write a functionality. It fast got out-dated since you wont think about everything when youre programming in UML.</p>


答:
Two points:

1/ The final goal is rerely to have C, it is to have machine language.  In your examples, the final goal is to have JavaScript or CSS because those are somewhat the machine language of the browsers.

2/ Compiling to C was (is still) a popular choice for first implementation of compiled languages. That step is usually masked as it is just an artifact of the implementation and not a useful one.  (In the same way, compilers which generate assembly instead of object files usually mask the fact they spawn an assembler to transform the assembly in object code).  Later version may compile directly to assembly or machine language.  (Nowadays, targeting existing VM like the Java and .NET one are also popular, and one may argue the availability of LLVM make targeting C often less pertinent.)

Title: Syntactic Sugar for old languages


问:
How can I take a list of tokens (of variable number) and know what each token means?
I have to read a text document with data formatted as follows: (a couple of examples)

```<code>07 M W F 1400 1450 C 2004
M W F 0900 1030 EN 2036
06 M T R 1300 1350 EN 1003
17 T R 0900 1015 EN 1052
</code>```

The problem I'm having is, once splitting up these strings with .split(" ", -1), I get a different number of tokens for many of them, and the position of the difference varies in the first two "sections".

The first part of the string is supposed to represent a scheduling code. It's optional, as can be seen by it being missing in the second line. The second area depicts which days of the week this schedule applies to. It could be anywhere from one to five days, but in these examples there are only 2 or 3. Then the rest are pretty much static: Start time, end time, building code and room number.

What I need to do is construct multiple objects for this schedule based on this info (one object for each day), and I'm not sure how to proceed. How can I tell, when iterating over the array of tokens, what each token represents? I thought about using a switch statement, but that would only work for the days, as there are 5 of them.

The following is the code I (tentatively) plan to use for this object.

```<code>public class TimeSlot {

  private Day day;
  private int startTime;    // # of minutes after midnight
  private int endTime;
  private Room room;
  private String slot;

  /**
   * Default constructor. Create an instance of TimeSlot.
   * @param day   day of the week
   * @param start start time of lecture represented as minutes after midnight
   * @param end   end time of lecture represented as minutes after midnight
   * @param room  room the class takes place in
   */
  public TimeSlot(String slot, Day day, int start, int end, Room room) {
    this.slot = slot;
    this.day = day;
    this.startTime = start;
    this.endTime = end;
    this.room = room;
  }
}

enum Day {
  MONDAY,
  TUESDAY,
  WEDNESDAY,
  THURSDAY,
  FRIDAY,
  SATURDAY,
  SUNDAY;
}

public class Room {

  private String buildingCode;
  private String roomNumber;

  public Room(String building, String room) {
    this.buildingCode = building;
    this.roomNumber = room;
  }

  public String buildingCode() {
    return buildingCode;
  }

  public String roomNumber() {
    return roomNumber;
  }

}
</code>```

答:
First step is to shoot the person who chose to collect the data that way: variable numbers of fields without identifiers is pretty tedious. Also, day of the week is ridiculous for a room scheduling app, unless you're scheduling it for months at a time (with some kind of default end date?). This would be a non-issue if you stored dates.

In this case however, you can probably just parse through the arguments, and figure out where you are by whether or not you're seeing an integer in the data field. From what you've said it looks like the data breaks down pretty clearly:

First position is either an integer or a character (string? Is Thursday "Th"?). After that you have a variable number of non-integers until you get to the start time, then you have the end time, then building, then room. You're going to have to know this anyway (because Java is staticly/strongly typed), so might as well make use of it.


答:
As much as people sometimes complain about regular expressions, this is a perfect scenario for using them.  I'm not familiar with the syntax for Java myself (but here's a reference), but I can tell you that you're going to want the pattern:

```<code>(\d+ )?([MTWRF] )+(\d+) (\d+) (\w+) (\d+)
</code>```

You can test it out here.

Step by step, this means:

(\d+ )? - If they exist, capture any number of digits followed by a space.

([MTWRF] )+ - Capture a letter from the set MTWRF followed by a space, as many times as it happens (but at least once).

If you want to enforce the 1-5 rule, replace the + with {1,5}, so it becomes ([MTWRF] ){1,5}.

If you want to include Saturday and Sunday, add S and U inside the [] block (order doesn't matter), so it would become ([UMTWRFS] )+.

(\d+) - Capture a series of digits.  If you want to enforce four digits, replace the + with {4} so it becomes (\d{4}), or simply put in four \d characters to make (\d\d\d\d).

(\d+) - Capture another series of digits. See above for modifications.

(\w+) - Capture a series of letters

(\d+) - Capture a last series of digits. See above for modifications.

You then can access each capture - if the first one doesn't match, it should be empty. If the second one matches multiple letters, you can just get those by splitting on spaces.  All other ones don't even have stray spaces for you to worry about.

Title: How can I take a list of tokens (of variable number) and know what each token means?

Body:
I have to read a text document with data formatted as follows: (a couple of examples)

```<code>07 M W F 1400 1450 C 2004
M W F 0900 1030 EN 2036
06 M T R 1300 1350 EN 1003
17 T R 0900 1015 EN 1052
</code>```

The problem I'm having is, once splitting up these strings with .split(" ", -1), I get a different number of tokens for many of them, and the position of the difference varies in the first two "sections".

The first part of the string is supposed to represent a scheduling code. It's optional, as can be seen by it being missing in the second line. The second area depicts which days of the week this schedule applies to. It could be anywhere from one to five days, but in these examples there are only 2 or 3. Then the rest are pretty much static: Start time, end time, building code and room number.

What I need to do is construct multiple objects for this schedule based on this info (one object for each day), and I'm not sure how to proceed. How can I tell, when iterating over the array of tokens, what each token represents? I thought about using a switch statement, but that would only work for the days, as there are 5 of them.

The following is the code I (tentatively) plan to use for this object.

```<code>public class TimeSlot {

  private Day day;
  private int startTime;    // # of minutes after midnight
  private int endTime;
  private Room room;
  private String slot;

  /**
   * Default constructor. Create an instance of TimeSlot.
   * @param day   day of the week
   * @param start start time of lecture represented as minutes after midnight
   * @param end   end time of lecture represented as minutes after midnight
   * @param room  room the class takes place in
   */
  public TimeSlot(String slot, Day day, int start, int end, Room room) {
    this.slot = slot;
    this.day = day;
    this.startTime = start;
    this.endTime = end;
    this.room = room;
  }
}

enum Day {
  MONDAY,
  TUESDAY,
  WEDNESDAY,
  THURSDAY,
  FRIDAY,
  SATURDAY,
  SUNDAY;
}

public class Room {

  private String buildingCode;
  private String roomNumber;

  public Room(String building, String room) {
    this.buildingCode = building;
    this.roomNumber = room;
  }

  public String buildingCode() {
    return buildingCode;
  }

  public String roomNumber() {
    return roomNumber;
  }

}
</code>```

Body:
As much as people sometimes complain about regular expressions, this is a perfect scenario for using them.  I'm not familiar with the syntax for Java myself (but here's a reference), but I can tell you that you're going to want the pattern:

(\d+ )?([MTWRF] )+(\d+) (\d+) (\w+) (\d+)

You can test it out here.

Step by step, this means:

(\d+ )? - If they exist, capture any number of digits followed by a space.

([MTWRF] )+ - Capture a letter from the set MTWRF followed by a space, as many times as it happens (but at least once).

If you want to enforce the 1-5 rule, replace the + with {1,5}, so it becomes ([MTWRF] ){1,5}.

If you want to include Saturday and Sunday, add S and U inside the [] block (order doesn't matter), so it would become ([UMTWRFS] )+.

(\d+) - Capture a series of digits.  If you want to enforce four digits, replace the + with {4} so it becomes (\d{4}), or simply put in four \d characters to make (\d\d\d\d).

(\d+) - Capture another series of digits. See above for modifications.

(\w+) - Capture a series of letters

(\d+) - Capture a last series of digits. See above for modifications.

You then can access each capture - if the first one doesn't match, it should be empty. If the second one matches multiple letters, you can just get those by splitting on spaces.  All other ones don't even have stray spaces for you to worry about.


问:
Product backlog- when do task hours get estimated?
I am wondering if when developing a product backlog do tasks have hours estimated for them. To confirm, i can talking about a product backlog here not a sprint backlog as I know it does have. </p>

答:
I don't really use hours to estimate the product backlog, as often it's in a language that doesn't readily lend itself to hour estimates (And ideally, that's what the sprint backlog should be for, as I understand the process).

We use the points system (or rounded Fibonacci if you prefer), and scale the tasks by complexity. Such as "Ok, user A wants graphical representation of these elements", and through experience, you know that can be tricky but not not time consuming. If a 1 is easy, and 21 is complex, it might be a 4. User B wants an interactive graph that can be changed on the fly by adding/subtracting data points/business units. That gets a 15.

Also, don't feel like you absolutely HAVE to detail points for all of your backlog. Some items may never be gotten to. Do enough for the foreseeable future, and work from the top down as it is (or should be) already in priority order.

You also have to consider the ROI, in that a 3 task may be quicker than a 5 task, but the 6 task will produce X% more revenue. Is that enough to bump it up? You have to decide.


答: You could try processing the tokens from the back since these, according to yourself, have a consistent format. Then when you get on to the variable part you will have to make sure that the days of the week are valid, and if they're not assume it's the scheduling code. Of course, check that that's numeric too.</p>


问:
Kanban: How to choose work item size
Starting with Kanban, I'm not sure about how granular my work items should be. While you find lots of concrete recommendations about how to choose the WIP, most of the Kanban tutorials I've read stay quite vague about the size of a work item (= a card on the board).

For planning and estimation, people often recommend to keep the size of an  item small, say 2-16 hours. Does the same apply for Kanban? Is there always a 1:1 mapping from my plan to the board?

If there's no best practice or general recommendation, which factors would influence my choice of work item granularity?

答:
It's up to you, and what you feel comfortable with.  I pick a size of "easily understandable and doable".  Sometimes that means getting started, realizing it's more complicated and breaking it down more and/or being more clear.

It's just tasks on a list.  Size isn't all that important, unless your trying to measure throughput, in which case your probably better off using fibonacci numbers or t-shirt sizings for that instead of hours.

If you're trying to forecast, I'd recommend using either fibnacci or t-shirt sizing for size estimate, and then track how long the difference numbers or t-shirt sizes actually take.  Then feed the averages into your forecasting process.

Title: Kanban: How to choose work item size


答:
I'd say make items the size they can be easily made to. "Start with what you do now" is one principle of Kanban. So split the work like you do now. "Agree to pursue incremental, evolutionary change" is another principle. Start implementing small changes if you see problems in the way you split work.

Don't get hung up on analysing and designing your "Kanban process" beforehand. Start doing and continue doing things that work and try to fix things that don't work.

Title: Kanban: How to choose work item size

Body:
Starting with Kanban, I'm not sure about how granular my work items should be. While you find lots of concrete recommendations about how to choose the WIP, most of the Kanban tutorials I've read stay quite vague about the size of a work item (= a card on the board).

For planning and estimation, people often recommend to keep the size of an  item small, say 2-16 hours. Does the same apply for Kanban? Is there always a 1:1 mapping from my plan to the board?

If there's no best practice or general recommendation, which factors would influence my choice of work item granularity?


问:
How do you split work on web apps?
About a year ago at my workplace we decided to get into developing a web app for internal use (as part of a more intricate system which is irrelevant to this question). No one really had experience in web development, so probably some of our decisions were wrong, but all in all we've had success with the tool we were developing. Since we did have experience developing in Python, we chose Django as our platform.

My question is about "who does what". The way we split our work was: there is one team which handles all the Python code - which means all the Django urls, views and models, as well as the actual backend to handle asynchronous task execution (something a bit like Celery). A different team (more precisely, a single person in a different development group - but this is just implementation) is responsible for the templates (data binding), javascript, design, HTML, CSS, etc.

We have been working like this, as I said, for about a year now. I'm starting to think that maybe the line of responsibilities between the two teams is wrong. The reason is that there's a pretty big overhead whenever we need to interact - which is a lot. For example, when we add a new table and we want to display it, we need to let the "frontend guy" know what the url would be and what it would contain. Then we need to integrate out work to see if everything's alright. Sometimes we didn't pass enough context to the template to make it work and there's a slow ping-pong of information between us.

So my question is this - what is the accustomed way to split work on web apps? Who takes care of the different modules - models, views, urls, templates, design, user experience, HTML, CSS, javascript?

答: I don't think a strong split like this is necessary. Pretty much all devs I've been working with were capable of coding backend and front end. We did have a go-to css/html guy, though, who could make the markup look good, so we could throw in a rough styling, code around it, and push it over to him to polish. Sometimes we also had people who would create design mock-ups and think about the UI flow.</p>

Title: How do you split work on web apps?


问:
Where did Java go wrong on the client?
Not talking about the recent Java/Oracle debacle here, but something I've been wondering recently.

When I first started programming, Java was the big thing client-side, however these days you hardly ever see a Java applet whereas Flash and Javascript are ubiquitous.

Where did Java go wrong? Did Sun decide to concentrate on the server-side and let client-side stagnate? How did Flash become dominant over Java? Flashy (no pun intended) graphics? Marketing?

Never having been a Java developer, I've not followed this closely so I'm interested to hear your thoughts.

答:
The whole idea of cross platform UI is flawed. Windows uses very different layout, mechanisms, key presses etc etc to Mac OS X. To make a seamless experience that doesn't irritate the user, you have to make your app exactly right for that platform, taking advantage of the platform specifics used.

Any cross platform solution will always suffer from a "least common denominator" - only the very basic things the different UIs have in common can be used and that makes for a bad user experience all around. This is the same argument all-mighty-steve uses against flash on the iPhone.

I think the irritate the user issue is a very fundamental "soft" problem, that people from a tech perspective often miss.

Title: Where did Java go wrong on the client?


问:
Will it be a wrong idea to have

  Hello

```

答:
There are a few technical reasons for having your css in a file vs a style tag:

The ability to use a css minifier (I don't believe minifiers work on style tags)

To have the css file be able to cached by the browser.

Some opinion based reasons to use a file:

You can use a wonderful css preprocessor like Sass (Compass) or Less.

You are maintaining two ways to add css to your application.

My personal preference is to use Compass to keep separate files for each page and then use it to compile them all into one file.  That single file would be included by every page.  If down the road the files need be separated for whatever reason they always can be but it is not worth the hassle in the meantime.

Title: Will it be a wrong idea to have <style> in <body>?

Body:
In below code i placed internal style sheet with in body tag, instead of having in head.
For Single-Page-Application I am considering to do this for styles that is only applicable to that page alone, rather than having separate pagespecific.css file.

Is there a scenario where this has downside as i am not putting the same in head section?

```<code><!-- myPartial.html starts here -->
<!-- Like to keep styles unique to this html right here in this file -->
<div>
  <style>
    body { background-color: red; }
    #myText { color: white; }
  </style>

  <span id='myText'>Hello</span>
</div>
<!-- myPartial.html ends here -->
</code>```


答:
A style element inside the body element violates HTML syntax rules. (Except that according to HTML5 drafts, it is allowed in some conditions, if the scoped attributes is present; this attribute is supported by some browsers.) On the other hand, browsers don’t care. The division into head and body elements is theoretical.

Yet, you gain nothing by using the invalid syntax, as opposite to placing style inside head. The only excuse would be technical limitations, in some authoring environments, that might prevent you from putting anything into the head part.

The issue of using a style element vs. an external stylesheet via link is completely orthogonal to this question.

Edit: As of HTML 5.2, style elements within body are explicitly allowed. w3.org, HTML 5.2, "The style element"

ContentLicense: CC BY-SA 4.0


答:
I agree with the other answers: Don't worry too much about the size, try it and improve - that's the Kanban way :-).

To still give you some concrete values, here's what our team does:

Minimum size is about 30 minutes - smaller cards cause too much overhead and clutter the board. If something needs to be done that takes <30 minutes, it (usually) gets added to a related card.

We aim for a maximum of one work day, because ideally you don't want to carry an open task to the next day, but that does not always work out. We sometimes have tasks that take two or three days, maybe even a week, but these are outliers, and we actively try to avoid these.

Finally, if you find that a task is larger than anticipated, it is perfectly acceptable to split it even after you started it. Break of the part that is done, change the card accordingly and finish it, and create a new card for what is left. That way you can already have a partial result (e.g. if you must ship), and the remaining work is visible.

Title: Kanban: How to choose work item size


问:
What is an integration test exactly?
My friends and I have been struggling to classify exactly what is an integration test.

Now, on my way home, I just realised, that every time I try to give a real world example of an integration test, it turns out to be an acceptance test, ie. something that a business person would say out loud that specs out what the system should be delivering.

I checked the Ruby on Rails documentation for their classification of these testing types, and it's now completely thrown me.

Can you give me a short academic description of an integration test with a real world example?

答:
Integration testing is nothing but checking the connection and correctness of data flow between two of more modules.

For Example: When we compose a mail(one module) and send it to some valid user ID(second module), the integration testing is to check whether the sent mail is there in the sent items.

Title: What is an integration test exactly?


问:
Why do we still use floats?
I understand why floats served a purpose in the past.  And I think I can see why they're useful in some simulation examples today.  But I think those example are more exceptional than common.  So I don't understand why floats are more prevalent in simple simulations rather than very high precision integers.

A classic argument is that floats provide a greater range, but high precision integers can meet this challenge now. For example: with modern 64-bit processors, we can do fast integer calculations up to 2^64. The solar system is a little less than 10 billion km in width. 10 billion km divided by 2^64 is about 5 microns. Isn't being able to represent position within the solar system to the precision of half a human hair enough?

On the flip-side, rounding errors from floating calculations can present problems.  You need to consider the scale of the calculations to make certain that you're not inadvertently introducing error to your simulation.

So why do personal computers even need FPUs anymore?  Why not just leave floats to the supercomputers?

答:
Physical characteristics of the universe (like the number of atoms in it) are not useful to determine the boundaries of number sizes, because useful calculations exist using numbers having wider ranges.

Floating point numbers are a tradeoff between accuracy and range.  They deliberately give up some accuracy to achieve greater range.

OwnerDisplayName: anon

Title: Why do we still use floats?


答:
Because most of the processors that you use in your day to day life are not modern day 64 bit processors with crazy fast integer calculations or an over abundance of space. Most of your processors are 8-16 bit devices which run things like your car, microwave, or watch.

Besides, what happens when you need to talk about a half of a unit, like a half of a gallon, or a half a human hair? Whole numbers are great, but then you end up talking in notations like 6.4216×1030 which, while accurate, isn't how humans naturally think.

Title: Why do we still use floats?

Body:
I understand why floats served a purpose in the past.  And I think I can see why they're useful in some simulation examples today.  But I think those example are more exceptional than common.  So I don't understand why floats are more prevalent in simple simulations rather than very high precision integers.

A classic argument is that floats provide a greater range, but high precision integers can meet this challenge now. For example: with modern 64-bit processors, we can do fast integer calculations up to 2^64. The solar system is a little less than 10 billion km in width. 10 billion km divided by 2^64 is about 5 microns. Isn't being able to represent position within the solar system to the precision of half a human hair enough?

On the flip-side, rounding errors from floating calculations can present problems.  You need to consider the scale of the calculations to make certain that you're not inadvertently introducing error to your simulation.

So why do personal computers even need FPUs anymore?  Why not just leave floats to the supercomputers?


答:
Using a float instead of a high precision integer (with conversions!) is simply easier and faster.  I can type in

```<code>float myVar = 0.15; //my value...
</code>```

and move on to the rest of the logic of my simulation.  I don't have to spend extra time thinking about converting to int and making sure that all of my scales are correct.

And the results end up being good enough.  I'll happily trade speed of development over ridiculous levels of presumed, relative accuracy within my work.

Title: Why do we still use floats?

Body:
Using a float instead of a high precision integer (with conversions!) is simply easier and faster.  I can type in

float myVar = 0.15; //my value...

and move on to the rest of the logic of my simulation.  I don't have to spend extra time thinking about converting to int and making sure that all of my scales are correct.

And the results end up being good enough.  I'll happily trade speed of development over ridiculous levels of presumed, relative accuracy within my work.


答:
Because switching to integers doesn't solve anything. The problem with floats isn't that they have inaccuracies, it's that half the people using them don't pay any attention to what's going on. Those same people aren't going to pay proper attention to the units they are using when they use an integer, and a different set of screw ups will happen.

Repeat after me: There is NO silver bullet.

Title: Why do we still use floats?


问:
Separating entities in the business logic layer
I am going to start a project, which in the BLL would have something like:

Jumper

Map

Record

I need to keep track of all those, so I will make probably classes which hold them, e.g.:

JumperList

MapList

RecordList

First of all, is that a good practice to hold all the objects and is it good if I separate them like:

BLL.Entity for the Jumper, Map, Record
and
BLL.List for JumperList, MapList, RecordList

Okay, I may have written it in a confusing way. What I meant was, is it good to make it like that:

```<code>BLL.Entity
 - Jumper
 - Map
 - Record
BLL.List
 - JumperList
 - MapList
 - RecordList
</code>```

答:
Separating is often good practise. But i prefer Repository, not List. And also look at this separation:</p>

```<code>Bll.Jumper
    +JumperEntity
    +JumperRepository
Bll.Map
    +MapEntity
    +MapRepository
Bll.Record
    +RecordEntity
    +RecordRepository
</code>```

Body:
Separating is often good practise. But i prefer Repository, not List. And also look at this separation:

Bll.Jumper
    +JumperEntity
    +JumperRepository
Bll.Map
    +MapEntity
    +MapRepository
Bll.Record
    +RecordEntity
    +RecordRepository


答:
I'm working on a report as I type this.  One of the fields is a long milliseconds of duration that I got from somewhere else.  This is going to be sent to Microsoft Excel and the duration units it uses is decimal days (1.25 = 1 day, 6 hours).

Sure, you can subdivide a range from the lowest possible value to the largest and have integer units stepping between them, but thats a really awkward unit to work with in most cases.

There are three times that come into play when working with computers:

Time it takes to code

Time it takes to run

Time it takes to maintain

When working with integers rather than floating point, you're trading times 1 and 3 for time 2 to run faster.  But here's the thing... I don't need it to run fast.

If there's a rounding error in the 10th decimal place in calculating a decimal time, thats fractions of a second that I don't care about (the report is HH:MM:SS - not HH:MM:SS.000).  They don't get rounded into what I'm dealing with or presenting.  Floating point is good enough.

Calculating the area of a circle for a graph or where pi finds its way into probabilities with only integers is not fun.  Pi is not 3.

Its also faster for me to work with floating point in many places.  1.5 is 1.5 not (15 with a scale of 1).  So I can write my code faster and the person maintaining it can read it faster and work with it.

If you need to use fixed point precision (money) or pure integer math for speed certain applications (simulating galaxies colliding and nuclear bombs), by all means, use them.  But for most things, floating point is just fine if you really aren't dealing with those specialized situations.

That's just working with one end of the scale.  The numbers that can be subdivided between 0 and 264 (or however many bits you are using).  264 is about 1019.  But what if you need to work with 1020 or 10200? There are problems that work in this domain that aren't restricted to super computers.  There are times when regular simulations and games use floats - often because of restrictions on the library, but they use them there too. Sometimes its just easier.

Related on gamedev.SE: About floating point precision and why do we still use it

Title: Why do we still use floats?


问:
How maintainable are automated refactorings?
Resharper offered to turn my loop:

```<code>foreach (JObject obj in arr)
{
    var id = (string)obj["Id"];
    var accountId = (double)obj["AccountId"];
    var departmentName = (string)obj["DeptName"];
    i++;
}
</code>```

...into a LINQ statement. I acquiesced, and it produced this:

```<code>int i = 1 + (from JObject obj in arr let id = (string) obj["Id"] let accountId = (double) obj["AccountId"] select (string) obj["DeptName"]).Count();
</code>```

Gee whillikers, jumpin' Jehoshaphat, and Heavens to Murgatroid!

This makes me wonder if the robots becoming smarter than me is a good thing; how maintainable is that? Answer: it's not, since I can't understand it; R# may just as well have converted it to machine code, for all I can grok it.

I have to admit, though, it's "cool."

At what point does the perfect become the enemy of the good in this kind of scenario?

UPDATE

On a second pass through, R# tells me for that line of LINQ, "Local variable "i" is never used"

Letting it remove it, the line becomes:

```<code>var arr = JsonConvert.DeserializeObject<JArray>(s);
</code>```

Hmm! Now that's grokkable; the reason I was breaking the elements down into individual vars before was so that I could see what was in them:

```<code>MessageBox.Show(string.Format("Object {0} in JSON array: id == {1}, accountId == {2}, deptName == {3}", i, id, accountId, departmentName));
</code>```

...but with that messagebox commented out, I guess the above is better after all.

答:
One rule of thumb I use is: "is this code easier to read?"

A refactoring may initially look cool, it may use something different than what you would normally do.  However, at the end of the day, you're better off with code which is easier to understand than the "hotness" a computer gives you.

So, if a computer gives me code which is difficult for me to grok quickly, I'd likely reject its suggestion.


答:
LINQ is very powerful.  But we should always be cautious on jumping on it.  Don't get me wrong, I love LINQ and for many cases, it is a beautiful tool.  In your case, your code was perfectly readable, and yet the LINQ version obfuscates your intentions and suddenly the programmer has to figure out exactly what is going on.

Your version is clear, concise, and full of intent.

The LINQ version is an abomination, by comparison.

Title: How maintainable are automated refactorings?

Body:
Resharper offered to turn my loop:

```<code>foreach (JObject obj in arr)
{
    var id = (string)obj["Id"];
    var accountId = (double)obj["AccountId"];
    var departmentName = (string)obj["DeptName"];
    i++;
}
</code>```

...into a LINQ statement. I acquiesced, and it produced this:

```<code>int i = 1 + (from JObject obj in arr let id = (string) obj["Id"] let accountId = (double) obj["AccountId"] select (string) obj["DeptName"]).Count();
</code>```

Gee whillikers, jumpin' Jehoshaphat, and Heavens to Murgatroid!

This makes me wonder if the robots becoming smarter than me is a good thing; how maintainable is that? Answer: it's not, since I can't understand it; R# may just as well have converted it to machine code, for all I can grok it.

I have to admit, though, it's "cool."

At what point does the perfect become the enemy of the good in this kind of scenario?

UPDATE

On a second pass through, R# tells me for that line of LINQ, "Local variable "i" is never used"

Letting it remove it, the line becomes:

```<code>var arr = JsonConvert.DeserializeObject<JArray>(s);
</code>```

Hmm! Now that's grokkable; the reason I was breaking the elements down into individual vars before was so that I could see what was in them:

```<code>MessageBox.Show(string.Format("Object {0} in JSON array: id == {1}, accountId == {2}, deptName == {3}", i, id, accountId, departmentName));
</code>```

...but with that messagebox commented out, I guess the above is better after all.


问:
Can I distribute open-source software that uses the syntax/interface of a proprietary program (Stata)?
Stata is a proprietary statistical program used largely by economists. I want to write a basic multiple regression package that uses the same commands as Stata, e.g., regress var1 var2 var3, robust if var4[_n - 1] < .

Is it legal (in the US) to distribute source code that does this under an open-source license? In other words, does any IP protection apply to the command syntax used by proprietary software?

答:
The general guiding principle of licensing software is that you're not licensing the computer language that the application was written in, but rather, the application so created by the language.

In other words, you are licensing the behavior of the application that is represented  by the code written in the language, not the language itself.  Since you're talking about the language itself, licensing has nothing to do with it.  In fact, you're not bound by Stata's license unless you agree to it, by using their software.

So licensing has nothing to do with it, from Stata's point of view.

The real question is, is the Stata language itself protected by copyright or patent?  If you want to host a Stata interpreter that you have written yourself, using the same language specification that Stata uses, you should check with Stata to see if it runs afoul of any copyright or patent issues.


问:
How to avoid big and clumsy UITableViewController on iOS?
I have a problem when implementing the MVC-pattern on iOS. I have searched the Internet but seems not to find any nice solution to this problem.

Many UITableViewController implementations seems to be rather big. Most examples I have seen lets the UITableViewController implement <UITableViewDelegate> and <UITableViewDataSource>. These implementations are a big reason why UITableViewControlleris getting big. One solution would be to create separate classes that implements <UITableViewDelegate> and <UITableViewDataSource>. Of course these classes would have to have a reference to the UITableViewController. Are there any drawbacks using this solution? In general I think you should delegate the functionality to other "Helper" classes or similar, using the delegate pattern. Are there any well established ways of solving this problem?

I do not want the model to contain too much functionality, nor the view. I believe that the logic should really be in the controller class, since this is one of the cornerstones of the MVC-pattern. But the big question is:

How should you divide the controller of a MVC-implementation into smaller manageable pieces? (Applies to MVC in iOS in this case)

There might be a general pattern for solving this, although I am specifically looking for a solution for iOS. Please give an example of a good pattern for solving this issue. Please provide an argument why your solution is awesome.

答:
I have recently wrote an article about how to implement delegates and data sources for UITableView: http://gosuwachu.gitlab.io/2014/01/12/uitableview-controller/

The main idea is to split responsibilities into separate classes, like cell factory, section factory, and provide some generic interface for the model that UITableView is going to display. Diagram below explains it all:


问:
Dynamically vs Statically typed languages studies
Do there exist studies done on the effectiveness of statically vs dynamically typed languages?

In particular:

Measurements of programmer productivity

Defect Rate

Also including the effects of whether or not unit testing is employed.

I've seen lots of discussion of the merits of either side but I'm wondering whether anyone has done a study on it.

答:
Link to discussion of ACM paper "An Experiment About Static and Dynamic Type Systems" (2010) by Stephan Hanenberg article (referenced by Lorin Hochstein in a previous post).

Conclusion: Productivity for similar quality was higher in a dynamic
language.

Potential biases/validity issues: Experimental subjects were all students. Also, limited
variety of the programming tasks (subjects were asked to implement a scanner and parser).

ACM paper "Do Programming Languages Affect Productivity?" (2007) by Delorey, Knudson, and Chun.

Conclusion: JavaScript, Tcl, Perl more productive than C# C++ and Java. Python and PHP fall in the middle.

Potential biases/validity issues: No measure of quality (such as bugs discovered post-release). No measure of reliability (is software written in statically typed languages more dependable?). Sample bias - all projects were open taken from open source CVS repositories. Also, no distinction between weakly and strongly typed languages (i.e. pointers).

Thesis "Empirical Study of Software Productivity and Quality" (2008) by by Michael F. Siok

Conclusion: Choice of programming language does not significantly influence productivity or quality. However, it does affect labor costs and "quality within the overall software projects portfolio".

Potential biases/validity issues: Restricted to avionics domain. Programming languages could have all been statically typed. I didn't read the thesis, so I cannot evaluate its rigor.

My opinion. Although there is weak evidence that dynamically typed languages are more productive, it is not conclusive. (1) There are many factors that were not controlled, (2) there are too few studies, (3) there has been little or no discussion about what constitutes an appropriate test method.


问:
How does one design his various architecture/business models?
I'm currently learning about various application design approaches and there's one thing I can't really get my head around.

Let's say I have a physical device in my network, an IP surveillance camera. I need a model that represents 'IP surveillance cameras' to work with them in my application, which might look like this:

```<code>public class IPCamera {

    public string     Token      { get; set; }
    public IPAddress  IPAddress  { get; set; }
    public string     RtspUri    { get; set; }

}
</code>```

Now, if I want to store the IPCamera into a database (e.g. with Entity Framework), I need maybe another properties and thus, another model with:

```<code>   public int         Id         { get; set; }
</code>```

Oh.. I want to access my application with via a WCF service. I can't use the object "IPAddress" here because it's not very serialization friendly, hence I need another model with a custom IP class that stores the IP address as string.

And last, an Android clients wants to access my data. I design a RESTful API using WebApi2. The client isn't interested in the cameras RTSPUri, but wants to know about the current state (is online, is offline).

I'm wondering: How to name all these models that they don't come in conflict? Should I design a model per each purpose/layer/service? And how to link/map them? With the adapter pattern?

答:
Now, if I want to store the IPCamera into a database (e.g. with Entity Framework), I need maybe another properties and thus, another model with...

No, you just need an ID property in your IPCamera class:

```<code>public class IPCamera {

    public int        ID         { get; set; }
    public string     Token      { get; set; }
    public IPAddress  IPAddress  { get; set; }
    public string     RtspUri    { get; set; }

}
</code>```

I can't use the object "IPAddress" here because it's not very serialization friendly, hence I need another model ...

No, you just need a ToString() method in your IPAddress class.

The client isn't interested in the cameras RTSPUri, but wants to know about the current state (is online, is offline).

Add an isOnline() method to your IPCamera class?

Body:
Now, if I want to store the IPCamera into a database (e.g. with Entity Framework), I need maybe another properties and thus, another model with...

No, you just need an ID property in your IPCamera class:

public class IPCamera {

    public int        ID         { get; set; }
    public string     Token      { get; set; }
    public IPAddress  IPAddress  { get; set; }
    public string     RtspUri    { get; set; }

}

I can't use the object "IPAddress" here because it's not very serialization friendly, hence I need another model ...

No, you just need a ToString() method in your IPAddress class.

The client isn't interested in the cameras RTSPUri, but wants to know about the current state (is online, is offline).

Add an isOnline() method to your IPCamera class?


问:
What are the advantages to developing with outdated technologies?
A little background:

I am working at a large company, using Windows XP and coding Winforms in VB6/VB.Net and some WebForms in VB.Net (95% maintenance code). I have one 4:3 19" screen. A more modern version of Windows isn't happening soon, neither is any greenfield work by the sounds of it!

I wasn't told about any of this when I joined the company, I was mislead to think I would be working with much more up to date technologies and frameworks.

I have much more up to date experience from previous jobs, both with more modern frameworks and other programming languages, and when I am catching up with developer friends from other companies all I hear about is how they are using the latest ASP MVC framework, or Vagrant/Ruby on Rails/etc and I am getting the green eyes!

I could sort myself out with another job pretty quickly, but I feel as though I should give this one more of a chance.

The question:

I am trying to convince myself that my current job isn't that bad. So what are the advantages to this sort of role? Are there advantages to working with outdated technologies? Maybe some techniques that I wouldn't pick up working with more modern ones? Or is this the sort of place where careers go to die, and I should get out while I still have my soul?

答:
This may not be exactly what you are asking, but I have some suggestions:

I think the greatest benefit is what you can offer your employer in terms of expertise when they eventually realize that they need to migrate. XP will be discontinued this year, so I imagine your IT department is already considering a migration strategy. (If not, get your resume ready, because they company is not going to be around long.)

With that in mind, it might be prudent to start compiling a list of advantages for migrating the primary software toolsets in conjunction with the OS/platform migration. Help educate your technically-unsavvy management chain as to the ROI with regard to new technologies. Your managers won't give a hoot about whiz-bang frameworks and tech-toys, but they should be very interested in your long-range projections regarding the comparative costs of ongoing maintenance expenses, future development, etc.

Along these same lines, you might take this opportunity to find out the satisfaction level of your customers (the employees using your software). What improvements would they love to see? What bugs drive them crazy? What features would significantly improve their efficiency? If you can show your employers that a new investment in technology would demonstratively impact their bottom line, you may well earn the title of Technical Migration Manager.

And THAT would look good on ANY resume.

UPDATE: Looks like you're not alone in your industry: "95% of World's ATMs run XP". Don't get me wrong: XP is great - I was always a fan. But reality is, once the security patches and updates end, XP will not be a viable product for a bank. Your job (for the sake of your bank's customers) is to graciously but persistently inform your managers that they will end up paying far more (in extended service arrangements or attack mitigation) to maintain XP past its retirement date. As @RobbieDee's link pointed out: you've got until 14 July, 2015. That's just enough time (if you start now) to design, implement and deploy a replacement system.

(But do NOT try to sell this idea to the guy who just signed off on the enterprise-wide XP-install. He is not your ally. With judgement like that, his days in that role are numbered. Just quietly work around him until wiser heads prevail.)


答:
Why do programmers still use floats? To the (generally good) answers which are already here, I would add:

Because most programming languages don't provide a "decimal" type, or at least don't make it as convenient to work with as a float. If they are built in to the language and convenient to work with, arbitrary-precision decimal numbers are much more intuitive and easier to work with than binary floating-point numbers, which give funny answers when you try to calculate things like 0.3 - 0.2.

Yes, you can use integers as fixed-point decimal numbers. Addition and subtraction work just fine, but extra steps are needed when doing multiplication/division (the result must be shifted up/down). That may have gained some performance 15 or 20 years ago, but on the CPUs of today, guess what? Just using floats is faster. Actually, floating point arithmetic is sometimes even faster than integer arithmetic!

Title: Why do we still use floats?


问:
What is an example of a computationally impossible business problem?
I have coworker who refuses to accept the reality that Turing machines (and Von Neuman machines by extension) cannot solve their own halting problem stating:

You can do anything with enough time and money.

He also dislikes theoretical problems arguing that:

In our field, we'll never run into those questions. We're application developers, not theoretical scientists.

Is there a good example of a business problem that is computationally impossible that I could use to help convince him of this?

答:
Not technically impossible, but...

Scheduling resources, with the goal of finding the ideal schedule that maximizes the use of time slots.  I was on a project once, in my earlier computing days, that had this requirement.  I worked on it awhile before I realized that it was NP-hard.

Other examples of problems that are not technically impossible, but are technically difficult, can be found here.

Most hard computational problems in business computing are not impossible, just impractical.  Your friend is right; you can solve most of them if you throw enough money at them.  But the argument is specious; the whole point of running a business is to make money, not lose it.

In daily practice, we talk about Turing completeness in a vague way, not to demonstrate some mathematical principle, but to illustrate (for example) the inadequacy of HTML and CSS as a complete vehicle for producing feature-complete programs.

Similarly, the Halting Problem is important to theorists, but it doesn't have much relevance to most businesses.


答:
You could use inheritance as in

```<code>public class StateFullIPCamera : IPCamera {
  public bool isOnline { get; set; }
}

public class IPCamera : EntityBase {
  public string Token { get; set; }
  public IPAddess IPAddress { get; set; }
  ...
}

public class EntityBase {
  public int Id { get; set; }
}
</code>```

Be careful though, if there are properties in the base classes which clients do not need, you should be returning them a different model. Never only populate some properties.

I upvoted Robert's answer because it is simple and makes sense.
As I commented there, I would suggest another api method specifically for getting the state of the camera and leave it off the model entirely.

Title: How does one design his various architecture/business models?

Body:
I'm currently learning about various application design approaches and there's one thing I can't really get my head around.

Let's say I have a physical device in my network, an IP surveillance camera. I need a model that represents 'IP surveillance cameras' to work with them in my application, which might look like this:

```<code>public class IPCamera {

    public string     Token      { get; set; }
    public IPAddress  IPAddress  { get; set; }
    public string     RtspUri    { get; set; }

}
</code>```

Now, if I want to store the IPCamera into a database (e.g. with Entity Framework), I need maybe another properties and thus, another model with:

```<code>   public int         Id         { get; set; }
</code>```

Oh.. I want to access my application with via a WCF service. I can't use the object "IPAddress" here because it's not very serialization friendly, hence I need another model with a custom IP class that stores the IP address as string.

And last, an Android clients wants to access my data. I design a RESTful API using WebApi2. The client isn't interested in the cameras RTSPUri, but wants to know about the current state (is online, is offline).

I'm wondering: How to name all these models that they don't come in conflict? Should I design a model per each purpose/layer/service? And how to link/map them? With the adapter pattern?

Body:
You could use inheritance as in

public class StateFullIPCamera : IPCamera {
  public bool isOnline { get; set; }
}

public class IPCamera : EntityBase {
  public string Token { get; set; }
  public IPAddess IPAddress { get; set; }
  ...
}

public class EntityBase {
  public int Id { get; set; }
}

Be careful though, if there are properties in the base classes which clients do not need, you should be returning them a different model. Never only populate some properties.

I upvoted Robert's answer because it is simple and makes sense.
As I commented there, I would suggest another api method specifically for getting the state of the camera and leave it off the model entirely.


答:
Many programmers are using floats because doubles are too slow or take too much memory. On good GPUs doubles are 4 times slower, while on "mediocre" GPUs (like all nVidia GeForce GPUs apart from the GeForce GTX Titan) can have up to 24x slowdown. Many GPUs don't support doubles at all.
That's why many developers (especially working with consoles) are forced to use floats. This often results in rough graphics and choppy unrealistic animation.

Update (for people having problems with inference):

The range of 64-bit signed integer is 2^63. The range of IEEE 754-2008 single-precision float is 2^(2^8)=2^256

Thus, the range of a single-precision floating-point numbers is 2^193 = 12554203470773361527671578846415332832204710888928069025792 times bigger than the rage of a signed 64-bit integer.

Single-precision floating-point numbers are not enough even for applications that don't require precise calculations (like animaion and games). Single-precision floating-point numbers are nearly unusable for anything requiring higher-precision, like physical simulation (even in games).

2 & 3 => 64-bit integers are very poor substitutes even for single-precision floating-point numbers.

Title: Why do we still use floats?


答:
General audio processing uses floats because these are sufficient and fast to compute, using higher precision than what 32bit float offers is purely useless; implementations said numerically "exact" would require much more processing power and might not fit real-time specs. Some specific implementations use fixed point, like for some (old) embeded platforms, but that's not the scope of your question. See http://broadcastengineering.com/audio/fixedpoint_vs_floatingpoint .

Most other signal processing & image processing algorithm implementations use floating point quite for the same reasons. Fixed-point or integer implementations are only derived from the floating point algorithms for specific purposes.

Title: Why do we still use floats?


问:
How to organise the different bits and pieces in an agile environment?
Trying to make our shop an agile environment, we struggle with some bits and pieces of that world. While not making it waterfally, we do have to have some sort of agreement on what a new feature needs to do. We follow the KISS and "minimally viable product" principle. Still, after discussing a story, we end up with:

UI/UX design

Acceptance criteria

Constraints

Use cases

Some extra specifications (like what fields to show in tables etc)

As tools we use JIRA, Greenhopper, Balsamiq, Glyphy and Confluence and they are working very well but we're not quite sure where to store which bits and how to make this work together well.

How do you guys approach that. Please include details on how far you go detailing the feature before development starts.

答: On UI-heavy stories, we attach PDFs, assets, and other items from the designers directly in the JIRA issue. A discussion tends to develop in the comments section of the issue and its subtasks as constraints, acceptance criteria, and specifications become clarified. We find this is pretty simple and doesn't get in the way too much. Sometimes we even paste content from emails into the issue. The {quote} wrapper works well for this.</p>


问:
Implementing Settings/Preferences in JavaScript
I am making a simple web app mostly in JavaScript. I was wondering as to how do I deploy settings/preferences? Do I just store user preferences somewhere and make use of if...else... statements all over the code?

I think that there must be a better alternative. I am know JS, jQuery & PHP and willing to learn anything new if at all required.

I have already made the app, only the settings are remaining. I know what options to give users and how to program them in js.

What's the most optimal way? How is it done in professional web apps and software made by companies (I am independent Student Developer - this is my first "BIG" project)?

EDIT:

For all the modifications that the settings are supposed to make (in this particular app), the whole js code base would litterally be filled with many branches of if...else...statements and I think that would make the code a lot harder to read and maintain.

In my app, the whole database table to be fetched from the database and the number and types of HTML DOM manipulation to be done, new elements to be added to HTML dom and whether some  are visible or not would change. How do I deal with all that?

答:
I think it depends on the nature of the settings.

Some settings are basically numbers, like number of results to display or a zoom factor or such like. These settings can be read from your settings structure (or API) as needed and plugged in as parameters to functions in your code. I think these are straightforward.

Other settings control functionality, like whether entire blocks of information are displayed. These naturally lead to branches in the logic of the app (if/else statements). If you want to eliminate these, use the strategy or delegate design patterns. You basically have a function preconfigured to follow one path or the other, and you pass that function as a parameter. The main code then becomes simple, and complexity is pushed to the set-up code that composes and selects the desired implementation functions.

If the logic that you think you need to generate your page is complex, and the content of the page is complex, some logic in the final implementation might be unavoidable. What you can do to keep it manageable is to rethink the logic and see if you can simplify it. I find this is often quite possible. Factoring out implementation from the logic that engages it can also make your code more manageable. In the main body you will have some logic that reads settings values and that invokes subroutines as needed. Well-selected parameters to those subroutines, including function parameters, might result in fewer of them overall. JavaScript lends itself to this model. Take advantage of it.

For example:

```<code>function addTable(tablename)
{
    while (readFromDatabase(tablename))
    {
        writeTableLine(...);
    }
}

function addGraph(tablename)
{
    while (readFromDatabase(tablename))
    {
        buildGraph(...);
    }
}

// in the main code:
var table1 = settings.getTable1name();
var table2 = settings.getTable2name();
var outputFunction = settings.shouldShowGraph() ? addGraph : addTable;

outputFunction(table1);
// more stuff
outputFunction(table2);
</code>```

The code above can output data from any number of tables in either table or graph form with no if statements.

Body:
I think it depends on the nature of the settings.

Some settings are basically numbers, like number of results to display or a zoom factor or such like. These settings can be read from your settings structure (or API) as needed and plugged in as parameters to functions in your code. I think these are straightforward.

Other settings control functionality, like whether entire blocks of information are displayed. These naturally lead to branches in the logic of the app (if/else statements). If you want to eliminate these, use the strategy or delegate design patterns. You basically have a function preconfigured to follow one path or the other, and you pass that function as a parameter. The main code then becomes simple, and complexity is pushed to the set-up code that composes and selects the desired implementation functions.

If the logic that you think you need to generate your page is complex, and the content of the page is complex, some logic in the final implementation might be unavoidable. What you can do to keep it manageable is to rethink the logic and see if you can simplify it. I find this is often quite possible. Factoring out implementation from the logic that engages it can also make your code more manageable. In the main body you will have some logic that reads settings values and that invokes subroutines as needed. Well-selected parameters to those subroutines, including function parameters, might result in fewer of them overall. JavaScript lends itself to this model. Take advantage of it.

For example:

function addTable(tablename)
{
    while (readFromDatabase(tablename))
    {
        writeTableLine(...);
    }
}

function addGraph(tablename)
{
    while (readFromDatabase(tablename))
    {
        buildGraph(...);
    }
}

// in the main code:
var table1 = settings.getTable1name();
var table2 = settings.getTable2name();
var outputFunction = settings.shouldShowGraph() ? addGraph : addTable;

outputFunction(table1);
// more stuff
outputFunction(table2);

The code above can output data from any number of tables in either table or graph form with no if statements.


问:
How can I take a list of tokens (of variable number) and know what each token means?
I have to read a text document with data formatted as follows: (a couple of examples)

```<code>07 M W F 1400 1450 C 2004
M W F 0900 1030 EN 2036
06 M T R 1300 1350 EN 1003
17 T R 0900 1015 EN 1052
</code>```

The problem I'm having is, once splitting up these strings with .split(" ", -1), I get a different number of tokens for many of them, and the position of the difference varies in the first two "sections".

The first part of the string is supposed to represent a scheduling code. It's optional, as can be seen by it being missing in the second line. The second area depicts which days of the week this schedule applies to. It could be anywhere from one to five days, but in these examples there are only 2 or 3. Then the rest are pretty much static: Start time, end time, building code and room number.

What I need to do is construct multiple objects for this schedule based on this info (one object for each day), and I'm not sure how to proceed. How can I tell, when iterating over the array of tokens, what each token represents? I thought about using a switch statement, but that would only work for the days, as there are 5 of them.

The following is the code I (tentatively) plan to use for this object.

```<code>public class TimeSlot {

  private Day day;
  private int startTime;    // # of minutes after midnight
  private int endTime;
  private Room room;
  private String slot;

  /**
   * Default constructor. Create an instance of TimeSlot.
   * @param day   day of the week
   * @param start start time of lecture represented as minutes after midnight
   * @param end   end time of lecture represented as minutes after midnight
   * @param room  room the class takes place in
   */
  public TimeSlot(String slot, Day day, int start, int end, Room room) {
    this.slot = slot;
    this.day = day;
    this.startTime = start;
    this.endTime = end;
    this.room = room;
  }
}

enum Day {
  MONDAY,
  TUESDAY,
  WEDNESDAY,
  THURSDAY,
  FRIDAY,
  SATURDAY,
  SUNDAY;
}

public class Room {

  private String buildingCode;
  private String roomNumber;

  public Room(String building, String room) {
    this.buildingCode = building;
    this.roomNumber = room;
  }

  public String buildingCode() {
    return buildingCode;
  }

  public String roomNumber() {
    return roomNumber;
  }

}
</code>```

答: You might consider using Scanner rather than String and split(). It seems like using Scanner's various hasNext() and next() methods would allow you to set up logic to fit your needs and check if the next entry in the file is an integer or not, or matches a certain pattern such as hasNext("M"). Scanner's default delimeter is a whitespace character, so it should work fine for your input file, though you can also set the delimeter to any valid regex expression using useDelimeter().</p>


问:
Should I use git and mercurial in the same directory?
I am looking for a solution for having revision control on framework code and project code at the same time. If I am using a MVC framework, there may be specific directories where I should put my project code. I want to easily apply framework updates using revision control while still keeping project code under a separate repository.

The solution I have come up with is to clone the framework repo using git, and then create a mercurial repo on top of it, and creating .gitignores and .hgignores so that they don't pick up on each other's code.

My directory structure would in theory look something like this:

Framework/ (git)

Framework_Code/ (git)

Models/ (git)

projectModel.php (hg)

Views/ (git)

projectView.html (hg)

Controllers/ (git)

projectController.php (hg)

Front_Controller.php (git)

Assuming I have the correct .gitignores and .hgignores, when there are framework updates I can do a simple

```<code>git pull
</code>```

And when I need to commit project code I can do

```<code>hg commit
</code>```

Is this a bad workflow? Are there any easier ways to set up something like this with either git or mercurial? I'm open to alternative solutions because this seems like something that someone smarter than me would have a solution for.

答:
This is a bad idea.

We have a similar setup in my company, but we use Git only. We have it so that the framework and project code are in separate branches, and then you can commit/push/pull independently.

The project branch is based off of the framework branch. This is convenient because if you make updates to the framework branch, you can just cleanly merge those changes into the project branch.


问:
What is meant by "Now you have two problems"?
There is a popular quote by Jamie Zawinski:

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.

How is this quote supposed to be understood?

答:
As you ask for it in 2014, it would be interesting to focus on programming languages ideologies of 1997 context comparing to today's context. I will not enter this debate here but opinions about Perl and Perl itself have greatly changed.

However, to stay in a 2013 context (de l'eau a coulé sous les ponts depuis), I would suggest to focus on reenactment in quotes using a famous XKCD comic that is a direct quote of Jamie Zawinski's one :

First I had problems to understand this comic because it was a reference to the Zawinski quote, and a quote of a Jay-z song lyrics, and a reference of GNU program --help -z flag2, so, it was too much culture for me to understand it.

I knew it was fun, I was feeling it, but I didn't really know why. People are often doing jokes about Perl and regexes, especially since it's not the hipstiest programming language, don't really know why it is supposed to be fun... Maybe because Perl mongers do silly things.

So the initial quote seems to be a sarcastic joke based on real life problems (pain?) caused by programming with tools that hurts. Just like a hammer can hurt a mason, programming with tools that are not the ones that a developer would choose if he could can hurt (the brain, the feelings). Sometimes, great debates about which tool is the best occurs, but it's almost worthless cause it's a problem of your taste or your programming team taste, cultural or economic reasons. Another excellent XKCD comic about this :

I can understand people feeling pain about regexes, and they do believe that another tool is better suited for what regexes are designed for. As @karl-bielefeldt answers your question with great expressivity comes great responsibility, and regexes are especially concerned by this. If a developer don't care of how s-he deals with regexes, it will eventually be a pain for people who will maintain the code later.

I will finish with this answer about quotes reenactment by a quote showing a typical example from Damian Conw ay's Perl Best Practices (a 2005 book).

He explains that writing a pattern like this:

```<code>m{'[^\\']*(?:\\.[^\\']*)*'}
</code>```

...is no more acceptable than writing a program like this:

```<code>sub'x{local$_=pop;sub'_{$_>=$_[0
]?$_[1]:$"}_(1,'*')._(5,'-')._(4
,'*').$/._(6,'|').($_>9?'X':$_>8
?'/':$")._(8,'|').$/._(2,'*')._(
7,'-')._(3,'*').$/}print$/x($=).
x(10)x(++$x/10).x($x%10)while<>;
</code>```

But it can be rewritten, it's still not pretty, but at least it's now survivable.

```<code># Match a single-quoted string efficiently...
m{ '            # an opening single quote
    [^\\']*     # any non-special chars (i.e., not backslash or single quote)
    (?:         # then all of...`
    \\ .        # any explicitly backslashed char
    [^\\']*     #    followed by any non-special chars
    )*          # ...repeated zero or more times
    '           # a closing single quote
}x
</code>```

This kind of rectangular shaped code is the second problem not regexes that can be formatted in a clear, maintainable and readable way.

Body:
As you ask for it in 2014, it would be interesting to focus on programming languages ideologies of 1997 context comparing to today's context. I will not enter this debate here but opinions about Perl and Perl itself have greatly changed.

However, to stay in a 2013 context (de l'eau a coulé sous les ponts depuis), I would suggest to focus on reenactment in quotes using a famous XKCD comic that is a direct quote of Jamie Zawinski's one :

First I had problems to understand this comic because it was a reference to the Zawinski quote, and a quote of a Jay-z song lyrics, and a reference of GNU program --help -z flag2, so, it was too much culture for me to understand it.

I knew it was fun, I was feeling it, but I didn't really know why. People are often doing jokes about Perl and regexes, especially since it's not the hipstiest programming language, don't really know why it is supposed to be fun... Maybe because Perl mongers do silly things.

So the initial quote seems to be a sarcastic joke based on real life problems (pain?) caused by programming with tools that hurts. Just like a hammer can hurt a mason, programming with tools that are not the ones that a developer would choose if he could can hurt (the brain, the feelings). Sometimes, great debates about which tool is the best occurs, but it's almost worthless cause it's a problem of your taste or your programming team taste, cultural or economic reasons. Another excellent XKCD comic about this :

I can understand people feeling pain about regexes, and they do believe that another tool is better suited for what regexes are designed for. As @karl-bielefeldt answers your question with great expressivity comes great responsibility, and regexes are especially concerned by this. If a developer don't care of how s-he deals with regexes, it will eventually be a pain for people who will maintain the code later.

I will finish with this answer about quotes reenactment by a quote showing a typical example from Damian Conw ay's Perl Best Practices (a 2005 book).

He explains that writing a pattern like this:

m{'[^\\']*(?:\\.[^\\']*)*'}

...is no more acceptable than writing a program like this:

sub'x{local$_=pop;sub'_{$_>=$_[0
]?$_[1]:$"}_(1,'*')._(5,'-')._(4
,'*').$/._(6,'|').($_>9?'X':$_>8
?'/':$")._(8,'|').$/._(2,'*')._(
7,'-')._(3,'*').$/}print$/x($=).
x(10)x(++$x/10).x($x%10)while<>;

But it can be rewritten, it's still not pretty, but at least it's now survivable.

# Match a single-quoted string efficiently...
m{ '            # an opening single quote
    [^\\']*     # any non-special chars (i.e., not backslash or single quote)
    (?:         # then all of...`
    \\ .        # any explicitly backslashed char
    [^\\']*     #    followed by any non-special chars
    )*          # ...repeated zero or more times
    '           # a closing single quote
}x

This kind of rectangular shaped code is the second problem not regexes that can be formatted in a clear, maintainable and readable way.


答:
Ideally, you wouldn't be storing your user-specific settings as discrete items access all over the place, but would instead have a single area of your application that gathers ALL settings as either the default or a user-specific override, and you would just reference the setting directly.

That is, assuming you have a loadUserSettings function that returns an object, instead of something like the following:

```<code>window.userSettings = loadUserSettings()

if(userSettings.favoriteColor) {
  document.backgroundColor = userSettings.favoriteColor;
} else {
  document.backgroundColor = 'blue';
}

if(userSettings.useSnark) {
  makeReply(userSettings.useSnark);
} else {
  makeReply(false);
}
</code>```

You would have

```<code>function loadSettings() {
  var userSettings = loadUserSettings();
  var baseSettings = {
    favoriteColor: 'blue',
    useSnark : false
  }
  window.settings = {};
  for(var s in baseSettings) {
    settings[s] = (userSettings[s] == undefined ? baseSettings[s] : userSettings[s])
  }
}

document.backgroundColor = settings.favoriteColor;
makeReply(settings.useSnark);
</code>```

You could also have your baseSettings be its own function, or use a framework's shallow-copy to do the same as the for loop above.  But the basic idea is to centralize the "settings" code into properties you can access directly as needed, rather than adding conditional branching everywhere to either do a default or follow the basic setting.

You will need some if branches, for things like "swagger when replying with snark", but their use would be minimal.

```<code>if(snark && settings.swaggerWhenReplyingWithSnark) {
  swagger();
}
</code>```

Title: Implementing Settings/Preferences in JavaScript

Body:
I am making a simple web app mostly in JavaScript. I was wondering as to how do I deploy settings/preferences? Do I just store user preferences somewhere and make use of if...else... statements all over the code?

I think that there must be a better alternative. I am know JS, jQuery & PHP and willing to learn anything new if at all required.

I have already made the app, only the settings are remaining. I know what options to give users and how to program them in js.

What's the most optimal way? How is it done in professional web apps and software made by companies (I am independent Student Developer - this is my first "BIG" project)?

EDIT:

For all the modifications that the settings are supposed to make (in this particular app), the whole js code base would litterally be filled with many branches of if...else...statements and I think that would make the code a lot harder to read and maintain.

In my app, the whole database table to be fetched from the database and the number and types of HTML DOM manipulation to be done, new elements to be added to HTML dom and whether some  are visible or not would change. How do I deal with all that?

Body:
Ideally, you wouldn't be storing your user-specific settings as discrete items access all over the place, but would instead have a single area of your application that gathers ALL settings as either the default or a user-specific override, and you would just reference the setting directly.

That is, assuming you have a loadUserSettings function that returns an object, instead of something like the following:

window.userSettings = loadUserSettings()

if(userSettings.favoriteColor) {
  document.backgroundColor = userSettings.favoriteColor;
} else {
  document.backgroundColor = 'blue';
}

if(userSettings.useSnark) {
  makeReply(userSettings.useSnark);
} else {
  makeReply(false);
}

You would have

function loadSettings() {
  var userSettings = loadUserSettings();
  var baseSettings = {
    favoriteColor: 'blue',
    useSnark : false
  }
  window.settings = {};
  for(var s in baseSettings) {
    settings[s] = (userSettings[s] == undefined ? baseSettings[s] : userSettings[s])
  }
}

document.backgroundColor = settings.favoriteColor;
makeReply(settings.useSnark);

You could also have your baseSettings be its own function, or use a framework's shallow-copy to do the same as the for loop above.  But the basic idea is to centralize the "settings" code into properties you can access directly as needed, rather than adding conditional branching everywhere to either do a default or follow the basic setting.

You will need some if branches, for things like "swagger when replying with snark", but their use would be minimal.

if(snark && settings.swaggerWhenReplyingWithSnark) {
  swagger();
}