答:
From your description, I would guess that your maps are purely bags of data, with all the logic in the Server methods. By pushing all chatroom logic into a separate class, you're still stuck with maps containing data.

Instead, try to model individual chatrooms, users etc. as objects. That way, you will be passing around only specific objects required for a certain method, instead of huge maps of data.

For example:

```<code>public class User {
  private String name;
  ...

  public void sendMessage(String message) {
    ...
  }
}

public class Chatroom {
  // users in this chatroom
  private Collection<User> users;

  public void add(User user) {
    users.add(user);
  }

  public void sendMessage(String msg) {
    for (User user : users)
      user.sendMessage(msg);
  }
}

public class Server {
  // all users on the server
  private Collection<User> users;

  // all chatrooms on the server
  private Collection<Chatroom> chatrooms;

  /* methods to handle incoming messages */
}
</code>```

Now it's easy to call a few specific methods to handle messages:

Want to join a chatroom?

```<code>chatroom.add(user);
</code>```

Want to send a private message?

```<code>user.sendMessage(msg);
</code>```

Want to send a public message?

```<code>chatroom.sendMessage(msg);
</code>```

Body:
From your description, I would guess that your maps are purely bags of data, with all the logic in the Server methods. By pushing all chatroom logic into a separate class, you're still stuck with maps containing data.

Instead, try to model individual chatrooms, users etc. as objects. That way, you will be passing around only specific objects required for a certain method, instead of huge maps of data.

For example:

public class User {
  private String name;
  ...

  public void sendMessage(String message) {
    ...
  }
}

public class Chatroom {
  // users in this chatroom
  private Collection<User> users;

  public void add(User user) {
    users.add(user);
  }

  public void sendMessage(String msg) {
    for (User user : users)
      user.sendMessage(msg);
  }
}

public class Server {
  // all users on the server
  private Collection<User> users;

  // all chatrooms on the server
  private Collection<Chatroom> chatrooms;

  /* methods to handle incoming messages */
}

Now it's easy to call a few specific methods to handle messages:

Want to join a chatroom?

chatroom.add(user);

Want to send a private message?

user.sendMessage(msg);

Want to send a public message?

chatroom.sendMessage(msg);

OwnerDisplayName: casablanca


问:
1 to 1 Comparison and Ranking System
I'm looking to create a comparison and ranking system which allows users to view 2 items, click on the one that they feel is the better one and then get presented with 2 more random items and continue to do this until they decide to stop.

In the background, I want the system to use these wins and loses to rank each item in an overall ranking table so I can then see what is #1 and what isn't.

I haven't got a clue where to begin with the formula, but I image I need to log wins and loses.

Any help/direction appreciated!

答:
Use the Elo algorithm!

From Wikipedia:

The Elo rating system is a method for calculating the relative skill levels of players in two-player games such as chess. It is named after its creator Arpad Elo, a Hungarian-born American physics professor.

It is actually used in many areas, not only games, as you can see here.

The general idea is, each person has a number. The higher the number, the better the player, and vice-versa. The winning person would gain a certain amount of points, and the losing person would lose the same amount of points. This amount is decided by the difference in rating between two competitors. The mathematical details can also be found on Wikipedia.

This sounds to be exactly what you need to implement. Just a couple of notes:

Yes, you should log wins-losses.

No, you should not keep track of streaks.

ContentLicense: CC BY-SA 3.0

Title: 1 to 1 Comparison and Ranking System


问:
How to get started with this project?
I recently finished my C++ programming class, and I'll start school in september. There is a limited online Parking spot registration and it always gets filled very quickly.

I would like to create a code that will quickly access the page and register for me.

The question is, how is this feasible? I guess I could use python, or Javascript, but I have no idea how to go on from my C++ class. What should I learn/do to program this code?

EDIT:
I posted this question on other forums also and I've been receiving a lot of answers like this: you need to use the library ...

Sorry if I'm a noob, but I've never used library and I have trouble understanding it. Is it like #include like the library will give me access to many functions by doing #inlude?

答:
Most likely, it involves sending the right HTTP POST request at the right time, and parsing the result to make sure it got submitted correctly.  You can do that with C++, although it would probably be easier in python if you already knew python.

The problem is, you have no way of testing the bot until the site goes live every semester, and no way of guaranteeing they won't change things between semesters.  And trust me, they will make changes to avoid bots hammering the site.  That's assuming they aren't already using captchas.  And if you accidentally break things, you will incur the wrath of the school administration.

My advice is to set an alarm for when registration opens and be ready in front of a web browser.

Title: How to get started with this project?


答:
First step is to profile the existing behaviour. Try installing fiddler, register normally. That should show you all the traffic that is passed between you and the site.

Second step is to emulate that behaviour. All modern languages support sending HTTP requests. You might find it simpler in a higher level language like JavaScript.

Title: How to get started with this project?

Body:
I recently finished my C++ programming class, and I'll start school in september. There is a limited online Parking spot registration and it always gets filled very quickly.

I would like to create a code that will quickly access the page and register for me.

The question is, how is this feasible? I guess I could use python, or Javascript, but I have no idea how to go on from my C++ class. What should I learn/do to program this code?

EDIT:
I posted this question on other forums also and I've been receiving a lot of answers like this: you need to use the library ...

Sorry if I'm a noob, but I've never used library and I have trouble understanding it. Is it like #include like the library will give me access to many functions by doing #inlude?


问:
Sporadic unittests or TDD?
I've read some basics about unit tests and TDD, but I find it hard to convince myself why TDD can have an advantage over only selected unittests.

I've read common arguments for TDD, but don't see the improvment compared to simple unittests. Maybe you can help to clarify:

TDD allows a loosely coupled, testable design -> I believe I can well imagine if a class is theoretically testable, without having to write tests; Loose coupling is a fundamental requirement that one can judge without refering to TDD?!

TDD gives confidence in refactoring -> Isn't it more efficient to add selected unittests as soon as you start refactoring? While you have to think what to cover by test, you still save writing a lot of tests.

TDD makes you define the interface first -> To me it seems some minor points are easier to decide while coding (which also agrees with agile?). It's even hard to predict a nested return data structure, but after coding I can often validate that I get what I expected. I made up the nested data while coding (a small unit) and see the behaviour. I'd save a lot of time writing the method first and using the validated result a posteriori to plug into a unittest.

from what I've read many (of course not all) sources state that TDD does require more development time even considering the benefit for debugging; merely the code quality improves -> Can it be that some programmers make different kinds of mistakes and for some TDD doesn't cover the type of mistakes they make anyway? So if my typical bugs are not approachable by predictable tests, it's not for me?

TDD aids changing teams, and larger interacting teams -> Is this a large issue? I can imagine it is, however as for the moment I program alone I cannot judge. How does TDD help teams in ways that... and here is the important point: other ways don't? It can force some discipline for less experienced team members, but apart from that any advantages?

答:
First i started creating Unit tests for where i thought it's necessary. To make it worse mostly i've done it after i wrote the code to be tested.

The fact that i could choose what to test i could (i'm not a strong person you can say) leave out important/risky code parts because i said: yeah that's never gonna broke.

The fact that i wrote the tests after the code made my code hard to test. It was not unit based but instead a collection of hacks (which can simply be because i'm not talented).

Once i've started TDD

I could never leave out stuff (or a lot less likely) from testing

I wrote only the code that was really needed

My code was well (or at least better) structured.

Happy coding!

Title: Sporadic unittests or TDD?


问:
Full Trust level: should be a concern?
Should I worry about the safety of my application if it runs in Full Trust level?

If yes, why? What damages could be done?

If the trust level should be a concern why it is the default level for asp.net applications instead of medium?

I know all the yes and no's between medium and full trust levels, but I can't see where this could be a serious risk to the application and server.

Considering this:

My ISP wants to (and will) change the trust level to Medium of an IIS asp.net mvc application running on a dedicated server.  This simply will break my application, since it relies heavily on System.Reflection namespace and it uses 3rd party assemblies which don't have the AllowPartiallyTrustedCallers defined.

The application runs under a specific user that has read only access to the application directory and only execute permission on stored procedures on the Sql Server. The authentication is via SSPI, so no passwords on web.config.

The ISP claims that if they let my application run in full trust they can not guarantee the security of my server. I never heard about a single case when the full trust was the cause to a security break. It seems to me that they are not sure about what they are doing.

I can't see a security flaw here. The only securiy flaw I can see in general is the password stealing from the web.config, but this is not possible in my current setup...

答:
Running in full trust is typically only a problem when you allow your application to run code that is written out of your control. For instance, when you download code from the internet, you like to sandbox this and this is what partial trust is for. For your ISP, they don't know your code and like to be able to sandbox it, since they have no idea what sorts of crazy things you are doing, or allowing others to do. For instance, your application might do on-the-fly compilation of C# code (pulled from the database) and run that. When a hacker is able to (SQL) inject this C# code in your database, he would be able to do absolutely anything within with in that process (which is quite a lot).

But I've got one question for you:

Do you trust your 3rd party components?

You like to run in full trust. Why? What code did you write needs full trust? Or is it the 3rd party components that need full trust? Why do they need full trust? Perhaps you are using a 3rd party component that is able to convert Word documents to PDF or the other way around and it need full trust. That sounds quite scary to me, since a hacker might be able to inject a malformed document that triggers a buffer overrun exception, which might be possible when the component uses unsafe code (which needs full trust). In that scenario, I would rather not use such a component, since it could be a serious threat to your application. Or you should sandbox that component to be run in partial trust in a different AppDomain.

The best advice I can give you is to do thread modeling. Look closely at the boundaries of your system. What are the inputs. What are the outputs. What are the risks. This is essential information to know how to mitigate the risk.

OwnerDisplayName: devundef

Title: Full Trust level: should be a concern?

OwnerDisplayName: Steven


问:
Can functional programming be used to develop a full enterprise application?
I am just beginning to learn Functional programming (FP). I come from a OOP world, where everything are objects, and most of them are mutable. I have a hard time wrapping around the concept that  functions don't have side effects.

If something is not mutable, how are common things objects like Employee or Person represented in FP.

Can FP be used to create a full fledged enterprise application?

答:
I have started learning about FP languages a couple of years ago (Haskell, Scala, Scheme) and, even though I am far from being an expert, I found out that they can make me extremely productive, for certain tasks more than C++ or Java.

IMO, some of the strengths of FP languages are:

They tend to be very concise, yet they retain a clear semantics.

You can use a declarative style and do not need to think too much about implementation details.

A rich type system like Haskell's can catch many logical errors very early (at compile time). As far as I know (not very much, actually), SML and Ocaml offer similar advantages.

Up to now, I have found the switch to the FP paradigm quite exciting and not too difficult once you spend enough time on it. (But how much time did I spend learning C or C++? Quite a lot!)

So I think that from a technical point of view it makes perfectly sense to develop a full enterprise application using a functional programming language.

Unfortunately this paradigm is not mainstream: most companies tend to adopt well-tested technologies only, so they will stay away from FP until they have enough evidence that it actually works, that there are enough developers, tools, libraries, frameworks. Therefore it is (much) more difficult to find a job in which you can do FP programming full.-time right now.

Maybe the current situation will change if the increasing use of multi-core processors will encourage to invest more in FP languages, which seem to be quite strong for writing concurrent software.

Also, there is a tendency to introduce some FP features into mainstream, non-functional languages like C#, C++ so that programmers can use some FP without the need of a complete paradigm switch. Maybe in ten years from now these languages will cover enough FP features that the switch to a purely functional language will be a lot easier.


问:
What do you call classes without methods?
What do you call classes without methods?

For example,

```<code>class A
{
  public string something;
  public int a;
}
</code>```

Above is a class without any methods. Does this type of class have a special name?

答:
Most of the time: An anti pattern.

Why? Because it faciliates procedural programming with "Operator" classes and data structures. You separate data and behaviour which isn't exactly good OOP.

Often times: A DTO (Data Transfer Object)

Read only datastructures meant to exchange data, derived from a business/domain object.

Sometimes: Just data structure.

Well sometimes, you just gotta have those structures to hold data that is just plain and simple and has no operations on it. But then I wouldn't use public fields but accessors (getters and setters).


答:
Always grant only the privileges you really need.

Let's say you work in a company. Your work is limited to the room A and B and you might, sometimes, go to the room E. If you're given the access to the room C, D and F, it means that if something wrong happens in those rooms, you will be among the suspects. To limit the risks for the company and, at the same time, make it safer for you to work there, you will be given only the accesses you actually need or might need, but only those.

Source code is the same thing. When everything has full access and something wrong happens, you have no idea what happened. If, on the other hand, the protected file was altered while the file can be changed only by two people in the company and by a specific application, you know that either one of those people did something wrong, or their accounts were hacked, or the specific application was hacked. It becomes much easier to find the root cause of the issue and to be very reactive face to a security threat.

There are other reasons to use partial trust:

The code you write may differ from what you've meant. Imagine that you're creating a tool which will sync the files in some mission-critical directories every ten minutes from the machine A to the backup machine B. You finish the nth version of the app late in the evening and you mistakenly ask the tool to remove the source files from the machine A. You also make a few mistakes so that it doesn't copy the files from A to B. If you work in a partial trust where your application cannot remove any file from anywhere, never, it will just gracefully fail. Instead, in full trust, it will do the harm, then tell that it succeeded, letting you discover the consequences days later.

You may use third party components that you don't always trust or can't verify. Steven already discussed this point.

Partial trust applications can be executed in the context where the user, executing the application, has a partial trust too. It applies to the ordinary users, as well as IIS, daemons (Windows Services), etc. If you write your app for partial trust, you are aware of the pitfalls. If your application is intended to run in full trust and is started by a user who has a very limited set of permissions, what will happen?

Working in partial trust forces you to learn things you don't usually use in full trust context. For example, what about IsolatedStorage? The advantages of isolated storage are not limited to the partial trust context (abstracting the way the information is stored; being sure that other non-malware applications will never access or overwrite the information you put there, etc.), but the feature is often ignored by people who work in full trust.

Some contexts force you to use partial trust. Silverlight is an example.

If your full-trust code accepts plugins, it is a security threat. Unless you specifically determine the permissions granted to the plugins code which runs in the sandbox (which has some issues too; for example, it's not obvious for the sandboxed plugins to change the UI, as well as you may encounter some issues when using cache), the code of the plugins run with the same privileges as your application. Given that those plugins can be written by a third party and contain harmful code, the user will blame your app and not the plugin from doing the harm.

Title: Full Trust level: should be a concern?

Body:
Should I worry about the safety of my application if it runs in Full Trust level?

If yes, why? What damages could be done?

If the trust level should be a concern why it is the default level for asp.net applications instead of medium?

I know all the yes and no's between medium and full trust levels, but I can't see where this could be a serious risk to the application and server.

Considering this:

My ISP wants to (and will) change the trust level to Medium of an IIS asp.net mvc application running on a dedicated server.  This simply will break my application, since it relies heavily on System.Reflection namespace and it uses 3rd party assemblies which don't have the AllowPartiallyTrustedCallers defined.

The application runs under a specific user that has read only access to the application directory and only execute permission on stored procedures on the Sql Server. The authentication is via SSPI, so no passwords on web.config.

The ISP claims that if they let my application run in full trust they can not guarantee the security of my server. I never heard about a single case when the full trust was the cause to a security break. It seems to me that they are not sure about what they are doing.

I can't see a security flaw here. The only securiy flaw I can see in general is the password stealing from the web.config, but this is not possible in my current setup...


答:
I would call such a class a mutable data holder, and have sometimes used a generic form:

```<code>class DataHolder<T>
{
   public T dat;
}
</code>```

Note that wrapping dat within a property will degrade performance and offer no benefit, since there's nothing that a property accessor could do (other than read/write the field) which wouldn't break some implementations.  Further, it may be necessary to use Interlocked methods with dat (or, if it's a struct, with fields thereof), but that wouldn't be possible if dat were wrapped in a property.

Note that while mutable data holders may be useful for types (mutable or not) which need to hold data, they cannot safely be used for data interchange in the same way that immutable types would.  For example, a statement like:

```<code>myData = myCollection.GetData(myKey);
</code>```

would have a clear meaning if GetData returned an immutable class type or a struct ("mutable" or not) which did not contain references to mutable data.  If it returned a mutable class object, however, it would be unclear whether any changes to that object would consistently be ignored by the underlying collection, consistently result in clean updates to it, or cause some irksome or unpredictable behavior meeting neither description.

If one wished to have a collection return data in a mutable object, the correct paradigm would often be something like:

```<code>var myData = new WhateverType();
myCollection.GetData(myKey, myData);
myData.ModifySomehow();
myCollection.StoreData(myKey, myData);
</code>```

Using that approach, there is a clear implication that GetData will cause myData to be populated with data from the collection, but myCollection would not be expected to keep a reference to it once the function was complete, nor would it use it for any other purpose.  StoreData would likewise copy information myData to its own internal data structure without keeping a reference.  Note that one advantage of this approach is that if the client code will be reading many data items within a loop, it may safely create one instance of myData outside the loop, and then reuse that same instance every time through.  Likewise, myCollection may be able to reuse the object instance associated with the key (copying data from the passed-in instance) without having to create a new instance.

Body:
What do you call classes without methods?

For example,

```<code>class A
{
  public string something;
  public int a;
}
</code>```

Above is a class without any methods. Does this type of class have a special name?

Body:
I would call such a class a mutable data holder, and have sometimes used a generic form:

class DataHolder<T>
{
   public T dat;
}

Note that wrapping dat within a property will degrade performance and offer no benefit, since there's nothing that a property accessor could do (other than read/write the field) which wouldn't break some implementations.  Further, it may be necessary to use Interlocked methods with dat (or, if it's a struct, with fields thereof), but that wouldn't be possible if dat were wrapped in a property.

Note that while mutable data holders may be useful for types (mutable or not) which need to hold data, they cannot safely be used for data interchange in the same way that immutable types would.  For example, a statement like:

myData = myCollection.GetData(myKey);

would have a clear meaning if GetData returned an immutable class type or a struct ("mutable" or not) which did not contain references to mutable data.  If it returned a mutable class object, however, it would be unclear whether any changes to that object would consistently be ignored by the underlying collection, consistently result in clean updates to it, or cause some irksome or unpredictable behavior meeting neither description.

If one wished to have a collection return data in a mutable object, the correct paradigm would often be something like:

var myData = new WhateverType();
myCollection.GetData(myKey, myData);
myData.ModifySomehow();
myCollection.StoreData(myKey, myData);

Using that approach, there is a clear implication that GetData will cause myData to be populated with data from the collection, but myCollection would not be expected to keep a reference to it once the function was complete, nor would it use it for any other purpose.  StoreData would likewise copy information myData to its own internal data structure without keeping a reference.  Note that one advantage of this approach is that if the client code will be reading many data items within a loop, it may safely create one instance of myData outside the loop, and then reuse that same instance every time through.  Likewise, myCollection may be able to reuse the object instance associated with the key (copying data from the passed-in instance) without having to create a new instance.


答:
These are known as Plain Old __ Objects (PO_Os) where the blank is Java or C or CIL, or whatever language you're using.

If they're being used as simple data blocks for communication, then they can be known as Data Transfer Objects (DTOs).

If they're representing some externally provided data, they can be known as Entities.

Title: What do you call classes without methods?


问:
Have you ever found yourself using a specific tool in favor of another just because it looks better?
I found that this was the case with Eclipse.
When I first started learning Java a lot of people told me to start with NetBeans because it's easier, comes with a lot of predefined functionality and most of the configuration is done by default. Indeed it seemed like an easy IDE but I just hated the way it looked. The UI to me was horrible.

Then I downloaded Eclipse. I was pretty impressed with it. Everything looked shiny, fonts looked awesome and the UI in general was amazing compared to NetBeans'. So I stayed with Eclipse.

Has something like this ever happen to you? Should the UI be of such a relevance to a programmer, is this bad ? The problem of the UI extends to everything for me, not only IDE's (e.g. even on linux I have to customize the WM the way I want before starting working with it).

答:
Not really. I don't have any design taste - my GUIs tend to be  rather garish to other people! What matters to me in a UI is: How easily and quickly can I get to what I need to do? If the most common tasks I need are buried in submenus under hidden switches, and can't be customized out to main menus (or better yet, buttons and shortcut keys) than I hate it.

There is a flip side to this too, though. If the common things are easy to do, but more complex stuff is hard to find, then the UI is equally bad. IMO the perfect example of this is Office 2007. All the basic operations are right up top; but if you need hanging indents, columns, or more advanced formatting options, they are harder to find. With the old menus, I could usually at least make an educated guess as to where the option was.

ContentLicense: CC BY-SA 2.5


答:
I'd call it struct or record because it is used for data storage and this is very common to languages like C as you can see there: struct (C programming language). So personally I would prefer use a struct instead of a class that is more suitable and readable:

```<code>struct A
{
  public string something;
  public int a;
}
</code>```

Usually they are used as DTOs (Data Transfer Object) as said the others.

Body:
I'd call it struct or record because it is used for data storage and this is very common to languages like C as you can see there: struct (C programming language). So personally I would prefer use a struct instead of a class that is more suitable and readable:

struct A
{
  public string something;
  public int a;
}

Usually they are used as DTOs (Data Transfer Object) as said the others.


问:
Is it OK for a function to modify a parameter
We have a data layer that wraps Linq To SQL. In this datalayer we have this method (simplified)

```<code>int InsertReport(Report report)
{
    db.Reports.InsertOnSubmit(report);
    db.SubmitChanges();
    return report.ID;
}
</code>```

On submit changes, the report ID is updated with the value in the database which we then return.

From the calling side it looks like this (simplified)

```<code>var report = new Report();
DataLayer.InsertReport(report);
// Do something with report.ID
</code>```

Looking at the code, ID has been set inside the InsertReport function as a kind of side effect, and then we are ignoring the return value.

My question is, should I rely on the side effect and do something like this instead.

```<code>void InsertReport(Report report)
{
    db.Reports.InsertOnSubmit(report);
    db.SubmitChanges();
}
</code>```

or should we prevent it

```<code>int InsertReport(Report report)
{
    var newReport = report.Clone();
    db.Reports.InsertOnSubmit(newReport);
    db.SubmitChanges();
    return newReport.ID;
}
</code>```

maybe even

```<code>Report InsertReport(Report report)
{
    var newReport = report.Clone();
    db.Reports.InsertOnSubmit(newReport);
    db.SubmitChanges();
    return newReport;
}
</code>```

This question was raised when we created a unit test and found that its not really clear that the report parameters ID property gets updated and that to mock the side effect behavior felt wrong, a code smell if you will.

答:
Usually programmers expect that only an object's instance methods can change its state.  In other words, I'm not surprised if report.insert() changes the report's id, and it's easy to check.  It's not easy to wonder for every method in the whole application if it changes the report's id or not.

I would also argue that perhaps ID shouldn't even belong to Report at all.  Since it doesn't contain a valid id for so long, you really have two different objects before and after insertion, with different behavior.  The "before" object can be inserted, but it can't be retrieved, updated, or deleted.  The "after" object is the exact opposite.  One has an id and the other doesn't.  The way they are displayed may be different.  The lists they appear in may be different.  Associated user permissions may be different.  They are both "reports" in the English sense of the word, but they are very different.

On the other hand, your code may be simple enough that one object will suffice, but it's something to consider if your code is peppered with if (validId) {...} else {...}.


问:
Is it a better practice pre-initialize attributes in a class, or to add them along the way?
I'm sorry if this is a ABSOLUTELY sophomoric question, but I'm curious what the best practices are out there, and I can't seem to find a good answer on Google.

In Python, I usually use an empty class as a super-catchall data structure container (sort of like a JSON file), and add attributes along the way:

```<code>class DataObj:
    "Catch-all data object"
    def __init__(self):
        pass

def processData(inputs):
    data = DataObj()
    data.a = 1
    data.b = "sym"
    data.c = [2,5,2,1]
</code>```

This gives me a tremendous amount of flexibility, because the container object can essentially store anything. So if new requirements crop up, I'll just add it as another attribute to the DataObj object (which I pass around in my code).

However, recently it has been impressed upon me (by FP programmers) that this is an awful practice, because it makes it very hard to read the code. One has to go through all the code to figure out what attributes DataObj actually has.

Question: How can I rewrite this for greater maintainability without sacrificing flexibility?

Are there any ideas from functional programming that I can adopt?

I'm looking for best-practices out there.

Note: one idea is to pre-initialize the class with all the attributes that one expects to encounter, e.g.

```<code>class DataObj:
    "Catch-all data object"
    def __init__(self):
        data.a = 0
        data.b = ""
        data.c = []

def processData(inputs):
    data = DataObj()
    data.a = 1
    data.b = "sym"
    data.c = [2,5,2,1]
</code>```

Is this actually a good idea? What if I don't know what my attributes are a priori?

答:
I would likely use the second approach, possibly using None to indicate invalid data.  It is true that it is difficult to read/maintain if you add attributes later.  However, more information on the purpose of this class/object would give insight as to why the first idea is a bad design: where would you ever have a completely empty class with no methods or default data?  Why wouldn't you know what attributes the class has?

It's possible that processData might be better as a method (process_data to follow python naming conventions), since it acts upon the class.  Given the example, it looks like it might be better as a data structure (where a dict may suffice).

Given a real example, you might consider taking the question to CodeReview, where they could help to refactor the code.


答:
How can I rewrite this for greater maintainability without sacrificing flexibility?

You don't. The flexibility is precisely what causes the problem. If any code anywhere may change what attributes an object has, maintainability is already in pieces. Ideally, every class has a set of attributes that's set in stone after __init__ and the same for every instance. Not always possible or sensible, but it should the case whenever you don't have really good reasons for avoiding it.

one idea is to pre-initialize the class with all the attributes that one expects to encounter

That's not a good idea. Sure, then the attribute is there, but may have a bogus value, or even a valid one that covers up for code not assigning the value (or a misspelled one). AttributeError is scary, but getting wrong results is worse. Default values in general are fine, but to choose a sensible default (and decide what is required) you need to know what the object is used for.

What if I don't know what my attributes are a priori?

Then you're screwed in any case and should use a dict or list instead of hardcoding attribute names. But I take it you meant "... at the time I write the container class". Then the answer is: "You can edit files in lockstep, duh." Need a new attribute? Add a frigging attribute to the container class. There's more code using that class and it doesn't need that attribute? Consider splitting things up in two separate classes (use mixins to stay DRY), so make it optional if it makes sense.

If you're afraid of writing repetive container classes: Apply metaprogramming judiciously, or use collections.namedtuple if you don't need to mutate the members after creation (your FP buddies would be pleased).

Title: Is it a better practice pre-initialize attributes in a class, or to add them along the way?

Body:
I'm sorry if this is a ABSOLUTELY sophomoric question, but I'm curious what the best practices are out there, and I can't seem to find a good answer on Google.

In Python, I usually use an empty class as a super-catchall data structure container (sort of like a JSON file), and add attributes along the way:

```<code>class DataObj:
    "Catch-all data object"
    def __init__(self):
        pass

def processData(inputs):
    data = DataObj()
    data.a = 1
    data.b = "sym"
    data.c = [2,5,2,1]
</code>```

This gives me a tremendous amount of flexibility, because the container object can essentially store anything. So if new requirements crop up, I'll just add it as another attribute to the DataObj object (which I pass around in my code).

However, recently it has been impressed upon me (by FP programmers) that this is an awful practice, because it makes it very hard to read the code. One has to go through all the code to figure out what attributes DataObj actually has.

Question: How can I rewrite this for greater maintainability without sacrificing flexibility?

Are there any ideas from functional programming that I can adopt?

I'm looking for best-practices out there.

Note: one idea is to pre-initialize the class with all the attributes that one expects to encounter, e.g.

```<code>class DataObj:
    "Catch-all data object"
    def __init__(self):
        data.a = 0
        data.b = ""
        data.c = []

def processData(inputs):
    data = DataObj()
    data.a = 1
    data.b = "sym"
    data.c = [2,5,2,1]
</code>```

Is this actually a good idea? What if I don't know what my attributes are a priori?


问:
Do people in non-English-speaking countries code in English?
I've heard it said (by coworkers) that everyone "codes in English" regardless of where they're from. I find that difficult to believe, however I wouldn't be surprised if, for most programming languages, the supported character set is relatively narrow.

Have you ever worked in a country where English is not the primary language?

If so, what did their code look like?

答: I worked with a 20-person team in Lima, Peru for several years on a classic ASP project. This was 10 years ago, so conventions may have changed, but at that time, all of the comments and variable names were in Spanish.


问:
Which aspect of normal forms do entity-attribute-value tables violate, if any?
I'm not asking if EAV tables are good or bad. I'm wondering if they are considered "normalized", and if not, why? If they aren't normalized, which normal form are they violating and why?</p>

答:
It's not Normalized

One of the Rules of Normalization is that : A field should have the same meaning in each row of the table.

Also the Table dosen't represent any specific Entity..

SQL Database Normalization Rules


答:
Maybe I'm over simplifying, but couldn't you just create a new database table called "ranks" foreign-keyed to the item?  Then, everytime a rank is set, just run this:

```<code>update `rank` set rankUp = rankUp + 1 where rankId = $whateverYourItemIdWouldBe
</code>```

Then, checking the highest value would be as simple as:

```<code>select * from `items` left join `rank` on items.itemId = ranks.itemId order by ranks.rankUp desc
</code>```

Title: 1 to 1 Comparison and Ranking System

Body:
I'm looking to create a comparison and ranking system which allows users to view 2 items, click on the one that they feel is the better one and then get presented with 2 more random items and continue to do this until they decide to stop.

In the background, I want the system to use these wins and loses to rank each item in an overall ranking table so I can then see what is #1 and what isn't.

I haven't got a clue where to begin with the formula, but I image I need to log wins and loses.

Any help/direction appreciated!

Body:
Maybe I'm over simplifying, but couldn't you just create a new database table called "ranks" foreign-keyed to the item?  Then, everytime a rank is set, just run this:

update `rank` set rankUp = rankUp + 1 where rankId = $whateverYourItemIdWouldBe

Then, checking the highest value would be as simple as:

select * from `items` left join `rank` on items.itemId = ranks.itemId order by ranks.rankUp desc


问:
Why is OOP difficult?
When I started using an object-oriented language (Java), I pretty much just went "Cool" and started coding. I've never really thought about it until only recently after having read lots of questions about OOP. The general impression I get is that people struggle with it. Since I haven't thought of it as hard, and I wouldn't say I'm any genius, I'm thinking that I must have missed something or misunderstood it.

Why is OOP difficult to understand? Is it difficult to understand?

答:
I think you can summarize the basic difficulty this way:

```<code>// The way most people think.
Operation - object - parameters
// Example:
Turn the car left.

// The way OOP works conceptually
Object - operation - parameters
// Example:
Car.Turn(270);
</code>```

Sure, people can get used to the mapping of "left" as 270, and yeah, saying "Car.Turn" instead of "turn the car" isn't such a huge leap.  BUT, to deal well with these objects and to create them, you have to invert the way you normally think.

Instead of manipulating an object, we're telling the object to actually do things on its own.  It may not feel difficult any more, but telling a window to open itself sounds odd.  People unused to this way of thinking have to struggle with that oddness over and over until finally it somehow becomes natural.

Title: Why is OOP difficult?

Body:
I think you can summarize the basic difficulty this way:

// The way most people think.
Operation - object - parameters
// Example:
Turn the car left.

// The way OOP works conceptually
Object - operation - parameters
// Example:
Car.Turn(270);

Sure, people can get used to the mapping of "left" as 270, and yeah, saying "Car.Turn" instead of "turn the car" isn't such a huge leap.  BUT, to deal well with these objects and to create them, you have to invert the way you normally think.

Instead of manipulating an object, we're telling the object to actually do things on its own.  It may not feel difficult any more, but telling a window to open itself sounds odd.  People unused to this way of thinking have to struggle with that oddness over and over until finally it somehow becomes natural.


问:
Does Fred Brooks' "Surgical Team" effectively handle the bus factor?
My team of 4 experienced developers works on a large, modular Windows application (approx. 200 KLoC). I have focused on the core codebase since the beginning of the project (3 years ago) and have gradually shifted to a semi-lead developer position, though I am not the team manager.

Our current iteration is a high-priority UI refresh requested by upper management, involving about 15 changes to the core codebase. When asked by the manager, I estimated that each of the 15 changes would take less than four hours for me to complete, a total of less than 7 work days. I then volunteered to perform the work. Instead, the manager decided to evenly divvy up all 15 tasks to all four developers.

In the three days since we started work, I have observed two things:

The other inexperienced team members completed about 1 or less task each.

Brook's Law in action:  I spent about half of my time providing assistance (attempting to coach them on using the components). As a result, I only finished 2 tasks myself, instead of the expected 5 or 6.

I approached my manager with my concern that we were running late and again suggested that I complete the remaining tasks. My request was kindly refused, and the stated reasons to split the load evenly was twofold:

Limit the truck/bus factor - ramping up other developers on these skills now, so that in the future any work can be given to anyone, not just me.

To eliminate a "bottleneck" (me) and get work done faster.

To be clear, I have no problems with: a) investing the time teaching, b) people touching my code, or c) job security. In fact, I regularly suggest to the team leader that I train other devs on certain aspects of the core codebase to reduce risk.

In this iteration we also have a large collection of high-priority bug fixes targeted, so it would seem that more progress could be made if the workload were redistributed.

In Mythical-Man-Month, Brooks' suggests a "Surgical Team" where every team is comprised of a lead + sub-lead (the manager and me), and some minor roles. I feel as though we are naturally falling into this organization, but my manager is working against it. I feel that the bus factor is already taken care of (the manager is well-versed in the core code), and that the bottleneck doesn't actually exist (involving more devs won't make the work go faster). I think that in this regard, a Surgical Team is a Good Thing.

These are my feelings, but I'm not an experienced manager, nor have we had to deal with the bus factor (knock on wood). Was Brooks right? Have you worked in a "Surgical Team" where the bus factor came into play? Are there better techniques to manage distributing expertise?

Similar questions:

How to increase the bus factor and specialize at the same time?

https://softwareengineering.stackexchange.com/questions/103718/always-keeping-2-people-expert-on-any-one-chunk-of-code

答: You may not be a bottleneck now, but eventually you will be if you continue to do all the work yourself.  Your manager realizes that it's important enough for you to learn to delegate to risk that your project be late--trust him.  Once you learn to let go, your juniors will start learning and producing much much more under your guidance.</p>


问:
Side-by-side Configuration on Linux/ELF
One of the best/worst Microsoft software innovations (great for compatibility; terrible for efficiency) has been Windows' Side by Side Configuration. This allows, among other things, for different components of a program to have multiple versions of the C/C++ runtime libraries loaded into the same process.

This has always impressed me because of the excellent backwards compatibility that it affords. For example, you can run an ancient program that links against very old C/C++ runtimes, and link it against or dynamically inject a new DLL that depends on a new C/C++ runtime, and all the separate instances of the runtimes will coexist simultaneously within the address space and will be called by the assembly that references them.

On Linux, however, binaries for which the source is not available tend to "rot" over time -- rather quickly. The reason is that most interesting programs eventually have to link back into libraries that are installed in your system directories (/usr/lib, etc). But since the C/C++ runtimes and the system libraries frequently change ABI, your program just stops working when you upgrade your distro.

This can also be caused, for example, by software with "backends" that eventually link to your system libraries. An example is OpenGL, which due to the variety and volatility of the implementations, cannot be provided by binary distributions. They simply must depend on the system's OpenGL implementation.

But if your system OpenGL links against libstdc++, you could potentially be dead in the water. What happens is that the old executable loads its local copy of libstdc++, and the OpenGL shared library loads the system's copy of libstdc++. The two conflict, and one of them refuses to load, and usually this means that OpenGL refuses to work and the program comes crashing down.

For a "mere" application developer, is something like WinSxS achievable on Linux without major architectural changes to the ELF binary format and Linux kernel ABI? Or is this something that would have to be built into the system libraries at compile-time and deployed over a long period of time by making changes to ELF, glibc, libstdc++, compilers, and so on?

答:
This may be foreign to Windows developers, but the solution is to provide the source, and recompile when the ABI changes.  You don't even need to provide all the source, just compile a wrapper on the interfaces that are likely to change, and link it with a binary holding the proprietary stuff.  Think of it as creating your own stable ABI.  Nvidia has been successfully following this model forever.  There are tools like DKMS that help make the recompilation process essentially invisible to the user.

If your product is popular enough, the community will even help you maintain the wrapper when the API changes.  For example, I ran community patches for Nvidia's driver before their official updates for kernel 2.6 were released.

Admittedly not as easy as just having your own library files for everything, but then again, for most applications it is as simple as that.  The wrapper solution is only necessary for a subset of software that's fairly low level.

Title: Side-by-side Configuration on Linux/ELF


答: Depending on the context, I call them Entities. On my boring business applications, they usually map 1:1 to my DER.


问:
How are entities with an identity and a mutable persistent state modelled in a functional programming language?
In an answer to this question (written by Pete) there are some considerations about OOP versus FP. In particular, it is suggested that FP languages are not very suitable for modelling (persistent) objects that have an identity and a mutable state.

I was wondering if this is true or, in other words, how one would model objects in a functional programming language. From my basic knowledge of Haskell I thought that one could use monads in some way, but I really do not know enough on this topic to come up with a clear answer.

So, how are entities with an identity and a mutable persistent state normally modelled in a functional language?

Here are some further details to clarify what I have in mind. Take a typical Java application in which I can (1) read a record from a database table into a Java object, (2) modify the object in different ways, (3) save the modified object to the database.

How would this be implemented e.g. in Haskell? I would initially read the record into a record value (defined by a data definition), perform different transformations by applying functions to this initial value (each intermediate value is a new, modified copy of the original record) and then write the final record value to the database.

Is this all there is to it? How can I ensure that at each moment in time only one copy of the record is valid / accessible? One does not want to have different immutable values representing different snapshots of the same object to be accessible at the same time.

答:
I'll take that you are talking about the stateless characteristic of pure functional language.

You take the initial state as an input, you return the final state as an output. Nothing fundamentally different from what you do in a language with a notion of state, excepted that you are more explicit about it and that can be tedious and less efficient(*).

Note that you don't necessarily have to modify all places which reference your object: they may hold a token and then you just have to modify the data structure which map the tokens to their current state. By then you are implementing a state-full system using a stateless language and you get back the issues of state-full languages.

(*) For instance I've looked for -- and not found -- the data structure which allow me to return in O(1) a modified copy of a data structure indexable by consecutive integers in O(1) as well.


答:
In short, each state of an entity is its own entity.  So in your classic "ordering" business logic, there's an Order entity, and an OrderVersion entity.  Both are immutable.  Logic that adds a line item takes the old version and a new OrderLineItemVersion as an input and returns a new OrderVersion entity.

It makes some things easier (particularly "undo" functionality), but some stuff is more difficult.

Title: How are entities with an identity and a mutable persistent state modelled in a functional programming language?

Body:
In an answer to this question (written by Pete) there are some considerations about OOP versus FP. In particular, it is suggested that FP languages are not very suitable for modelling (persistent) objects that have an identity and a mutable state.

I was wondering if this is true or, in other words, how one would model objects in a functional programming language. From my basic knowledge of Haskell I thought that one could use monads in some way, but I really do not know enough on this topic to come up with a clear answer.

So, how are entities with an identity and a mutable persistent state normally modelled in a functional language?

Here are some further details to clarify what I have in mind. Take a typical Java application in which I can (1) read a record from a database table into a Java object, (2) modify the object in different ways, (3) save the modified object to the database.

How would this be implemented e.g. in Haskell? I would initially read the record into a record value (defined by a data definition), perform different transformations by applying functions to this initial value (each intermediate value is a new, modified copy of the original record) and then write the final record value to the database.

Is this all there is to it? How can I ensure that at each moment in time only one copy of the record is valid / accessible? One does not want to have different immutable values representing different snapshots of the same object to be accessible at the same time.


答:
You are applying a constraint that may not be present or as significant to the degree you think it is.  Specifically, you're worried about the time until completion.  Your manager, on the other hand, does not appear as concerned by the perceived time constraints.

If you take the delivery time out of your question, you'll quickly start wondering why you're asking the question in the first place.

That's not to say that time is always available, and you did state this is a high priority request from upper management.  But you are not privy to all of the conversations your boss has had with them.  He may have negotiated for more time in order to have you spend that time training the other members of the team.

And while you feel the bus factor has already been addressed, your boss may be looking to the next request coming down the line that won't easily fit into 7 days of work by one of his star developers.  It's far safer to train the team on a smaller iteration where the objective magnitude of risk is much smaller.

I have been a critical bottleneck before; and honestly, it's not a pleasant place to be.  In my case, the VP of IT and I talked and we came up with a plan to permanently fix the issue.  It hurt, but it hurt a lot less than had I been trucked.

It's easy to get into the mindset of everything needing to be knocked out as quickly as possible.  A good manager spots the rare opportunities where a little delay (for cross-training / education) can pay significant dividends later on.

Title: Does Fred Brooks' "Surgical Team" effectively handle the bus factor?

Body:
My team of 4 experienced developers works on a large, modular Windows application (approx. 200 KLoC). I have focused on the core codebase since the beginning of the project (3 years ago) and have gradually shifted to a semi-lead developer position, though I am not the team manager.

Our current iteration is a high-priority UI refresh requested by upper management, involving about 15 changes to the core codebase. When asked by the manager, I estimated that each of the 15 changes would take less than four hours for me to complete, a total of less than 7 work days. I then volunteered to perform the work. Instead, the manager decided to evenly divvy up all 15 tasks to all four developers.

In the three days since we started work, I have observed two things:

The other inexperienced team members completed about 1 or less task each.

Brook's Law in action:  I spent about half of my time providing assistance (attempting to coach them on using the components). As a result, I only finished 2 tasks myself, instead of the expected 5 or 6.

I approached my manager with my concern that we were running late and again suggested that I complete the remaining tasks. My request was kindly refused, and the stated reasons to split the load evenly was twofold:

Limit the truck/bus factor - ramping up other developers on these skills now, so that in the future any work can be given to anyone, not just me.

To eliminate a "bottleneck" (me) and get work done faster.

To be clear, I have no problems with: a) investing the time teaching, b) people touching my code, or c) job security. In fact, I regularly suggest to the team leader that I train other devs on certain aspects of the core codebase to reduce risk.

In this iteration we also have a large collection of high-priority bug fixes targeted, so it would seem that more progress could be made if the workload were redistributed.

In Mythical-Man-Month, Brooks' suggests a "Surgical Team" where every team is comprised of a lead + sub-lead (the manager and me), and some minor roles. I feel as though we are naturally falling into this organization, but my manager is working against it. I feel that the bus factor is already taken care of (the manager is well-versed in the core code), and that the bottleneck doesn't actually exist (involving more devs won't make the work go faster). I think that in this regard, a Surgical Team is a Good Thing.

These are my feelings, but I'm not an experienced manager, nor have we had to deal with the bus factor (knock on wood). Was Brooks right? Have you worked in a "Surgical Team" where the bus factor came into play? Are there better techniques to manage distributing expertise?

Similar questions:

How to increase the bus factor and specialize at the same time?

https://softwareengineering.stackexchange.com/questions/103718/always-keeping-2-people-expert-on-any-one-chunk-of-code


答:
Actually, I would argue that you are following the "surgical team" model. Lucky!

Part of the point of said model is that the lower team members have an assistant role. When the team isn't doing heart surgery, then it is fine to move slower and give them a chance to practice some of their skills, or to cross train in responsibilities.

It is the job of the surgeon to examine and manage their team by looking for weak spots and resolving them, as well as being the top developer. You can't have a non surgeon (business manager) do this, because they don't understand the skills required, kind of like an apprentice to a master craftsman.

So, the manager is taking advantage of this opportunity to work on one of his other objectives. If during the course of it, some flaw is revealed in the team, he can deal with it before it becomes an issue. Say, by hiring another developer.

Or, the juniors might make a mistake. This is the perfect time for them to do so, since they have someone watching over their shoulder. Oscar Wilde said

Experience is simply the name we give our mistakes.

If these juniors never have an opportunity to make mistakes, then they will never improve. It won't just rob your team of experienced future developers, but in a sense, robs them of an opportunity they should have had.


答:
Our company used to work like you're suggesting.  We had only two people who understood a critical part of code.  Whenever a task came up in that part of the code, rather than spend a few weeks getting someone else up to speed, the task would be assigned to them because they could complete it in a couple days.  This actually worked pretty well for a while.

What happened is eventually their plate became so full that even though they might be able to finish a task in 2 days, it would take weeks to move to the top of their list.  Managers would have fierce verbal battles over whose task was more urgent.  Urgent dependent tasks would lie undone.

Eventually managers got sick of waiting and started getting their own teams trained up.  Yes, it was a lot slower for a while, but now our throughput is much better.

You may be in that first phase now where you can handle the work, but you have no way of predicting when you will move into the second phase.  Here's a hint:  it always happens at the most inconvenient time possible.  Your manager is right to take the hit when you still have some breathing room.

Yes, it's frustrating to watch someone struggle with something you could do much more quickly and easily yourself.  Try parenting a two year-old sometime.  You do it because it helps the whole team improve.  It's your manager's job to worry about the schedule.  If you're worried about the undone high priority bugs, challenge yourself to see how fast you can fix them.


问:
What is abstraction?
Is there a generally agreed upon definition for what a programming abstraction is, as used by programmers? [Note, programming abstraction is not to be confused with dictionary definitions for the word "abstraction."] Is there an unambiguous, or even mathematical definition? What are some clear examples of abstractions?

答:
Would Wikipedia's answer be good enough? http://en.wikipedia.org/wiki/Abstraction_%28programming%29

In computer science, the mechanism and practice of abstraction reduces and factors out details so that one can focus on a few concepts at a time.

Title: What is abstraction?


答:
The usual way to go about state changes in a pure language like Haskell is to model them as functions that take the old state and return a modified version. Even for complex objects, this is efficient because of Haskell's lazy evaluation strategy - even though you are syntactically creating a new object, it is not copied in its entirety; each field is evaluated only when it is needed.

If you have more than a few local state changes, things can become clumsy, which is where monads come in. The monad paradigm can be used to encapsulate a state and its changes; the textbook example is the State monad that comes with a standard Haskell install. Note, however, that a monad is nothing special: it's just a data type that exposes two methods (>>= and return), and meets a few expectations (the 'monad laws'). Under the hood, the State monad does exactly the same: take the old state and return a modified state; only the syntax is nicer.


问:
Is it smart to design a command and control server, that will monitor system resources and spin up/spin down servers at times of peak?
I am building an application that will be modular, in a way that it will be a set of separate systems communicating with each other. It uses Hadoop on all systems, and HBase on 3 of the 4.

Scaling will only be an issue on the non Hbase system, it uses it's own NoSQL like system. It will be a client facing system, and is very memory intensive, so each server can handle a limited number of users, before drastically dropping performance. All 4 systems have Zookeeper procedures & options built in.

Is it smart to design a command and control server, that will monitor system resources and spin up/spin down servers at times of peak? Would that set me up for failure, since if it faults the whole system can fail? How hard would it be to automate a task like that for Hadoop?

答:
At a basic level, you have to have something in place in order to scale up / down the size of your environment.

In your application's infancy, you'll provide that "something."  As you receive feedback from your systems (or more likely from your users complaining about your systems), you'll increase the capacity of the environment.

Automating that manual process is an excellent idea.

I would recommend designing an asynchronous method for querying your system nodes.  An asynchronous update will allow your C&C (command and control) center to keep operating even when a queried node is buried under load or has completely gone down.

But I'll contradict myself by mentioning ICMP and SNMP as two technologies to consider if you don't want to roll everything yourself.

If you're concerned about your C&C center going down, then the next level will be to setup redundancy between two or more C&C centers.  There are a number of schemes that you can use to minimize overhead in querying nodes.  I think this is beyond the scope of your question, so I won't delve into the details and will be content with having brought it up.

You are at risk of logic flaws within the C&C center.  But if you work through the logic diagram, you'll see you're either better or or no worse than you would have been otherwise.

C&C good, nodes good == you're good

C&C good, nodes fail == C&C fixes problem with more resource

C&C fail, nodes fail == you have resource starvation, but no worse than the case of the nodes failing anyway.

If your health monitor gets really good, it can send warning signals to the C&C center instead of outright error states.  The C&C can then have special logic to wait for the "all-clear" from that node.  If the all-clear doesn't arrive in a set amount of time, the C&C server can automatically spin up more nodes knowing that the troubled node never made it out of the danger zone.


答:
I'm not a functional language developer, so please shoot me down in flames if I have this wrong, but if right, it might be an interesting analogy.

I was once told that Excel is essentially a functional language. I'm not talking about VBA and so on, I'm talking about what happens on sheet.

So you have inputs, which may be tabular, individual cells or named ranges, and so on, and through a chain of operations you end up with a result, or many results. Change one input and it immediately flows through.

Does that analogy hold water?


问:
How can I make refactoring a priority for my team?
The codebase I work with daily has no automated tests, inconsistent naming and tons of comments like "Why is this here?", "Not sure if this is needed" or "This method isn't named right" and the code is littered with "Changelogs" despite the fact we use source control. Suffice it to say, our codebase could use refactoring.

We always have tasks to fix bugs or add new features, so no time is put aside to refactor code to be better and more modular, and it doesn't seem to be a high priority.

How can I demonstrate the value of refactoring such that it gets added to our task lists? Is it worth it to just refactor as I go, asking for forgiveness rather than permission?

答:
It sounds like your problems are more general.

The refactoring issue is both a symptom and a potential relief from part of the problem.

The Software Lead and the Team Allocate the Team's Time

From my experience, I think you may be encountering a problem that I call, "everybody's a software manager."  Product managers, project managers and sometimes system engineers and testers can be notorious for trying to micro-manage developers who probably already have an experienced software manager.  You may even have a few members on your team who believe their role is to manage.

If you are the software manager, make assignments for the refactoring you want, or better yet, have your team propose refactoring to you for your approval.  So as to not micromanage, you might have guidelines about age/author/size/context of code to be refactored that can be freely refactored vs. needing approval.  If a member of your team wants to massively refactor four big classes of complex old code he didn't write that are not part of his feature, his two week diversion is your problem, so you need a chance to say no.

You can sneak around, but I think it is better to just build your estimates carefully with time for analysis, design, coding, multiple forms of testing (at least unit and integration), refactoring, and risk as judged historically and by the lack of experience or clarity associated with the task.  If you have been too open about the workings of your team (or have members on your team who are), it might be wise to narrow communications channels so they go through you and discuss resources and results, not methods.

Early Project Choices Create a Vicious Cycle for Refactoring

Software maintenance is hard.  It is doubly hard if others in the organization are making choices at your expense.  This is wrong, but it is not new.  It has been addressed by Barry Boehm who is one of our great software writers who puts forward a management model he describes as Theory W.

http://csse.usc.edu/csse/TECHRPTS/1989/usccse89-500/usccse89-500.pdf

Often software developers are hammered to produce under the Theory-X management approach that says that workers are basically lazy and will not perform unless pounded into submission.  Boehm summarizes and contrasts his proposed model as follows:

"Rather  than  characterizing a manager  as  an autocrat (Theory X), a coach (Theory Y), or a facilitator (Theory Z), Theory W characterizes a manager’s primary role as a negotiator between  his  various constituencies, and a packager of project  solutions with win  conditions for all parties.  Beyond  this,  the manager is also a goal-setter, a monitor of progress towards goals, and an activist in seeking out day-to-day win-lose  or lose-lose project conflicts, confronting them, and changing them into win-win situations. "

Quick and Dirty is often Just Dirty

Boehm goes on to point out the reason things are so miserable for developers on the maintenance team.

"Building  a quick and sloppy product may be a low-cost, near-term “win” for the software developer and customer, but it will be a ‘‘lose’’ for the user and the maintainer."  Please note that in Boehm's model, the customer is more of a contract administrator instead of an end user.  In most companies, think of the product manager as a customer surrogate, or perhaps the person who buys the product for its feature list.

My solution would be to not release the original development team (or at least the original lead) until the code is refactored to at least meet coding standards.

For customer , I think it is reasonable to count the product manager as a customer surrogate, and the group of people rewarded for delivering something quick and dirty can certainly be expanded, so there is a big constituency for doing things the wrong way.

Refactoring is not Negotiable

Please don't back down from your role as a software manager.  You should have authority and discretion to use your team's time in process and product improvements.  In that role, you may need to negotiate your choices to make your team more professional.  However, with regard to process, don't negotiate with marketing, because in my experience, that is a losing game.  Negotiate with engineering management.  It shows you have vision.  Building a professional software team is an extension of their role, and is much more likely to be seen as a win-win.


答:
You could always use Alex Martelli's Bunch class. In your case:

```<code>class DataObj:
    "Catch-all data object"
    def __init__(self, **kwds):
        self.__dict__.update(kwds)

def processData(inputs):
    data = DataObj(a=1, b="sym", c=[2,5,2,1])
</code>```

That way, at least it's clear for the reader that data is just a dumb data store and one can see immediately which values are stored uner what name, since it all happens in one line.

And yes, doing things this way is in fact a good idea, sometimes.

Body:
You could always use Alex Martelli's Bunch class. In your case:

class DataObj:
    "Catch-all data object"
    def __init__(self, **kwds):
        self.__dict__.update(kwds)

def processData(inputs):
    data = DataObj(a=1, b="sym", c=[2,5,2,1])

That way, at least it's clear for the reader that data is just a dumb data store and one can see immediately which values are stored uner what name, since it all happens in one line.

And yes, doing things this way is in fact a good idea, sometimes.


问:
How to introduce code to a colleague
How do you go about introducing the codebase, which may be rather complex and tangled with a lot of "gotchas," to a new member of your team?

I think the easiest way would be to have the overall architecture laid out with diagrams, and take a couple weeks (or months) giving the new person well defined (and well scoped) tasks as he becomes more accustomed to the code.

However, as a consultant (and junior employee, at that,) I can't always have that either due to time constraints or team role designations. (I have been on this particular project twice as long as anybody else, so "junior" is in no way "knows less about the code/project.")

I've been tasked quite a few times now to introduce a new member to the project and code, and sadly each time I find I'm not much better at it than the one before.  I love diagrams and pictures, but often feel that they don't adequately account for the complexity in a system.   (What about all the little's "gotchas"?)

The project is getting to a point where we will be handing it off to the client, and to make things more challenging, the person I'll be doing a knowledge transfer with is essentially just out of college.  (Not that I'm much better when doing knowledge transfers with senior developers.)

I attend a user group once a month and other opportunities as they arise, so I'm not unused to be being introduced to new topics, but feel my ability to replicate effective knowledge sharing woefully inadequate.

Any advice would be greatly appreciated.  I am looking mostly for a guideline I can follow.  For example: Where do you start? How do you proceed? How do you cover unfamiliar technologies or patterns on the listener's part without taking all day?  Where do you tie in business logic vs. code-structure?

Thank you!

(As always, please feel free to edit the question as you see fit.)

答:
Support work is the best, take an easy bug and walk them through the areas where it'll be found. they will quickly learn how the code fits together. Naturally, they'll be coming over to ask questions about this bug and the codebase, but they'll get there (and you'll get a bug fixed). Often its much easier to figure things out with examples, similarly, its easier to work out a codebase by running through it in a debugger.

If you are unsure of the code changes (or they are, typically I'd be uncertain of my code fixes until I'm familiar with the codebase) then you can review it before checkin.

Of course, your existing ideas of broad overviews and block diagrams are essential first steps.

Title: How to introduce code to a colleague


问:
Multiple javaScript libraries | Emerging standards - compare to C++
It seems like there are many different styles to write JavaScript, in fact I've heard that JavaScript is an expressive language.

But the point of code is functionality (function) not expression (form).

Is there a library that will be adopted into the ECMA standard the way the STL and Boost Library were adopted in to the C++ standard?

答:
This seems unlikely. The free market is producing some very excellent libraries and those libraries have the advantage that there are no delays through standards bodies and there are NOT multiple somewhat incompatible implementations by different browsers - there is a single implementation that works nearly identically across multiple browsers.

Because there is a single implementation, there is no drive or particular benefit to push them into a standards body - in fact, they would probably decline and slow innovation if forced into standards bodies with only downside.

Further much of the point of these libraries is that a single implementation works across browsers so we NEVER want a standard to which multiple vendors implement.

We reserve that process for the much slower standards evolution where newer browsers add new features, some of which are experimental and some of which are new standards.  The jQuery-like libraries solve a completely different problem that would not be helped by the standards process.  Some good ideas from jQuery-like libraries may eventually make it into a standards process and become built-in features, but that will be years and years after they were first available in the 3rd-party library and could be considered an evolutionary process of good ideas getting standardized on and then built-in.  But, by then, the libraries will have moved onto the next set of functionality and will always be years ahead and will always be there to supply missing functionality to older browsers and to solve cross browser implementation issues.


答:
A programming abstraction is a simplified model of a problem.

For example, a TCP/IP connection is an abstraction over sending data.  You merely include an ip address and a port number and send it off to the API.  You aren't concerned with all the details of the wires, signals, message formats, and failures.

Title: What is abstraction?

Body: Is there a generally agreed upon definition for what a programming abstraction is, as used by programmers? [Note, programming abstraction is not to be confused with dictionary definitions for the word "abstraction."] Is there an unambiguous, or even mathematical definition? What are some clear examples of abstractions?


问:
Why is Javascript used in MongoDB and CouchDB instead of other languages such as Java, C++?
I asked this question on SO but was suggested to try here. So here it goes:

My understanding of Javascript so far has been that it is a client-side language that capture events and makes a web-page dynamic.

But on reading the comparison between MongoDB and CouchDB I noticed that both are using Javascript. This makes me wonder the reason behind the choice of JavaScript over other conventional languages.

I guess I am trying to understand the role of JavaScript and its advantages over other languages.

Update: I am not asking about the languages / drivers supported by the two databases. The comparison says:

Both CouchDB and MongoDB make use of Javascript. CouchDB uses Javascript extensively including in the building of views.

MongoDB also supports running arbitrary javascript functions server-side and uses javascript for map/reduce operations.

My lack of understanding pertains to why is Javascript being used at all for the backend work. Why is it preferred for building views in CouchDB, or for using map/reduce operations? Why C/C++ or Java were not used? What are the advantages in using Javascript for such back-end work?

答:
We will all have to eat humble-pie when we realize that JS is being used to write:

Databases

Servers

Operating System

and a myriad of libraries, frameworks, rendering engines, and compiling languages,

... because it is better.

Seriously, please... hear me out.
Do not shoot the messenger.

Ask Microsoft why they are building Windows 8 with JS as a first class citizen. Or Mozilla's new mobile OS, or IBM's Rivertrail, PhoneGap, ExtJS, or WebGL.

Would any of these companies or projects have been successful if the
  experts did not find something better in implementation?

The answer is... They did. We did.  So the theme here should be clear: there is a
  better way.

But, better is subjective: so we must drill-down and compare. What is better?

It started with AJAX... and it has not stopped.

Non-Blocking IO.
 This is a really big deal and worth knowing.
 In JS this is the callback pattern.
 It turns out, using callbacks can enable a non-blocking server: Node.js ~ about 8 lines of code.
 setTimeout() is a callback. Single-threaded asynchronous processing.

Flexibility.
  What?
  -Java and C have classes and interface, but are called object-oriented.
  JavaScript has only objects. But it is called ... something else.

-Having objects-only is a nice thing for flexibility, because members and methods are fully dynamic at runtime.
  -Prototypal inheritance is not scary. Some experts describe it as an object-packpack.
-JS is friendly on errors.
  -Code can mix together to result in Composite-Components, without much effort, or knowledge of... 'interfaces', 'abstraction', 'inheritance', 'encapsulation', 'polymorphism'. Good things, but like Nike, in JS; you just do it.

Data-Translation.
  With JSON, objects can be transferred front-to-back, back-to-front. No XML data translations. JSON is clearly simple.

Low learning curve.
  It is possible to cut and paste extremely complex code, then step-debug it into existence. I hear a colleague ... 'noobs'. But it is not just for noobs.

-It turns out that this is a really nice feature for Rapid Prototyping. And sites are popping up all over that leverage this design-in-browser thing, and more widely; runtime-prototyping. Checkout JSFiddle and CodePen, also MicroJS. GitHub.

```<code>Like Transformers, with JS, there is more than meets the eye.

It is a big deal.
</code>```

UPDATE: since this posting JavaScript is now used extensively by other languages.

```<code>In Java - check out Nashorn.
In C++ - check out Emscripten, or ASM.
And there are many more.

The big surprise since the original writing of this answer was JS cross-compilation.

It turns out that many languages can be compiled to JS.

And the community is encouraging that... CoffeeScript, Dart, etc.

This is not my specific area of expertise, but it is going on in big ways.

Simply put, we just don't know how the dynamism of JS is going to hash out yet.
</code>```

Body:
We will all have to eat humble-pie when we realize that JS is being used to write:

Databases

Servers

Operating System

and a myriad of libraries, frameworks, rendering engines, and compiling languages,

... because it is better.

Seriously, please... hear me out.
Do not shoot the messenger.

Ask Microsoft why they are building Windows 8 with JS as a first class citizen. Or Mozilla's new mobile OS, or IBM's Rivertrail, PhoneGap, ExtJS, or WebGL.

Would any of these companies or projects have been successful if the
  experts did not find something better in implementation?

The answer is... They did. We did.  So the theme here should be clear: there is a
  better way.

But, better is subjective: so we must drill-down and compare. What is better?

It started with AJAX... and it has not stopped.

Non-Blocking IO.
 This is a really big deal and worth knowing.
 In JS this is the callback pattern.
 It turns out, using callbacks can enable a non-blocking server: Node.js ~ about 8 lines of code.
 setTimeout() is a callback. Single-threaded asynchronous processing.

Flexibility.
  What?
  -Java and C have classes and interface, but are called object-oriented.
  JavaScript has only objects. But it is called ... something else.

-Having objects-only is a nice thing for flexibility, because members and methods are fully dynamic at runtime.
  -Prototypal inheritance is not scary. Some experts describe it as an object-packpack.
-JS is friendly on errors.
  -Code can mix together to result in Composite-Components, without much effort, or knowledge of... 'interfaces', 'abstraction', 'inheritance', 'encapsulation', 'polymorphism'. Good things, but like Nike, in JS; you just do it.

Data-Translation.
  With JSON, objects can be transferred front-to-back, back-to-front. No XML data translations. JSON is clearly simple.

Low learning curve.
  It is possible to cut and paste extremely complex code, then step-debug it into existence. I hear a colleague ... 'noobs'. But it is not just for noobs.

-It turns out that this is a really nice feature for Rapid Prototyping. And sites are popping up all over that leverage this design-in-browser thing, and more widely; runtime-prototyping. Checkout JSFiddle and CodePen, also MicroJS. GitHub.

Like Transformers, with JS, there is more than meets the eye.

It is a big deal.

UPDATE: since this posting JavaScript is now used extensively by other languages.

In Java - check out Nashorn.
In C++ - check out Emscripten, or ASM.
And there are many more.

The big surprise since the original writing of this answer was JS cross-compilation.

It turns out that many languages can be compiled to JS.

And the community is encouraging that... CoffeeScript, Dart, etc.

This is not my specific area of expertise, but it is going on in big ways.

Simply put, we just don't know how the dynamism of JS is going to hash out yet.


问:
Function declaration as var instead of function
More and more I'm seeing functions being declared like

```<code>var foo = function() {

    // things
};
</code>```

Instead of how I had learned, like

```<code>function foo() {

    // things
}
</code>```

What's the difference? Better performance? Scope? Should I be using this method?

答:
Your first example is an expression while the second example is a statement.  Defining functions as expressions allows for more flexibility in where the definition can occur, what you can assign it to, that you can pass it as a parameter, etc...

For example:

```<code>SomeThing('abc', function(a,b) {return a*b;});
</code>```

vs...

```<code>function tmp(a,b) {
    return a*b;
}

SomeThing('abc', tmp);
</code>```

More complex examples would become obcenely complicated without the function expression syntax.

Look at https://stackoverflow.com/questions/111102/how-do-javascript-closures-work

Body:
Your first example is an expression while the second example is a statement.  Defining functions as expressions allows for more flexibility in where the definition can occur, what you can assign it to, that you can pass it as a parameter, etc...

For example:

SomeThing('abc', function(a,b) {return a*b;});

vs...

function tmp(a,b) {
    return a*b;
}

SomeThing('abc', tmp);

More complex examples would become obcenely complicated without the function expression syntax.

Look at https://stackoverflow.com/questions/111102/how-do-javascript-closures-work


答:
var foo = function() {}  defines a variable that references an anonymous function.

function foo() {} defines a named function foo.

Either can be passed by name as function parameters and either can be instantiated if the intended use is for OOP.

At the end of the day, which one you use is largely dictated by your specific use-case (Javascript is fun like that ;)). If you end up using the former, I would strongly suggest that you name the function:

var foo = function MY_function() {}. This naming convention helps your debugger callstack not be useless.

Title: Function declaration as var instead of function

Body:
More and more I'm seeing functions being declared like

```<code>var foo = function() {

    // things
};
</code>```

Instead of how I had learned, like

```<code>function foo() {

    // things
}
</code>```

What's the difference? Better performance? Scope? Should I be using this method?


答:
In my experience a good way to bridge the gap between the broad overview an architecture diagram gives and the gritty details of actually working with the code is to do a drill-down of the system, i.e. what happens when a request arrives (for server code) or a user makes an input (for client code), then step by step explain all the layers of code that are involved.

Another way is a "guided tour" of the sourcecode, i.e. go through the packages/namespaces/modules/directories and explain what the code in each of them does in general. Of course this requires the code to be laid out somewhat logically.

Title: How to introduce code to a colleague

Body:
How do you go about introducing the codebase, which may be rather complex and tangled with a lot of "gotchas," to a new member of your team?

I think the easiest way would be to have the overall architecture laid out with diagrams, and take a couple weeks (or months) giving the new person well defined (and well scoped) tasks as he becomes more accustomed to the code.

However, as a consultant (and junior employee, at that,) I can't always have that either due to time constraints or team role designations. (I have been on this particular project twice as long as anybody else, so "junior" is in no way "knows less about the code/project.")

I've been tasked quite a few times now to introduce a new member to the project and code, and sadly each time I find I'm not much better at it than the one before.  I love diagrams and pictures, but often feel that they don't adequately account for the complexity in a system.   (What about all the little's "gotchas"?)

The project is getting to a point where we will be handing it off to the client, and to make things more challenging, the person I'll be doing a knowledge transfer with is essentially just out of college.  (Not that I'm much better when doing knowledge transfers with senior developers.)

I attend a user group once a month and other opportunities as they arise, so I'm not unused to be being introduced to new topics, but feel my ability to replicate effective knowledge sharing woefully inadequate.

Any advice would be greatly appreciated.  I am looking mostly for a guideline I can follow.  For example: Where do you start? How do you proceed? How do you cover unfamiliar technologies or patterns on the listener's part without taking all day?  Where do you tie in business logic vs. code-structure?

Thank you!

(As always, please feel free to edit the question as you see fit.)


问:
Is it ok to replace optimized code with readable code?
Sometimes you run into a situation where you have to extend/improve some existing code. You see that the old code is very lean, but it's also difficult to extend, and takes time to read.

Is it a good idea to replace it with modern code?

Some time ago I liked the lean approach, but now, it seems to me that it's better to sacrifice a lot of optimizations in favor of higher abstractions, better interfaces and more readable, extendable code.

The compilers seem to be getting better as well, so things like struct abc = {} are silently turned into memsets, shared_ptrs are pretty much producing the same code as raw pointer twiddling, templates are working super good because they produce super lean code, and so on.

But still, sometimes you see stack based arrays and old C functions with some obscure logic, and usually they are not on the critical path.

Is it a good idea to change such code if you have to touch a small piece of it either way?

答:
If I could teach the world one thing (about Software) before I die, I'd teach it that "Performance versus X" is a False Dilemma.

Refactoring is typically known as a boon for readability and reliability, but it can just as easily support optimization.  When you handle performance improvement as a series of refactorings, you can honor the Campsite Rule while also making the application go faster.  It is actually, at least in my opinion, ethically incumbent upon you to do so.

For instance, the author of this question has encountered a crazy piece of code.  If this person were reading my code, they would find that the crazy part is 3-4 lines long.  It's in a method by itself, and the method name and description indicates WHAT the method is doing.  The method would contain 2-6 lines of inline comments describing HOW the crazy code gets the right answer, despite its questionable appearance.

Compartmentalized in this way, you are free to swap out implementations of this method as you like.  Indeed, that's probably how I wrote the crazy version to begin with.  You are welcome to try, or at least ask about alternatives.  Most of the time you will find out that the naive implementation is noticeably worse (usually I only bother for a 2-10x improvement), but compilers and libraries are always changing, and who knows what you may find today that wasn't available when the function was written?


答:
function expression:

```<code>//someFunction(); //wouldn't work when uncommented
var someFunction = function(){ alert('yay'); };
</code>```

The func expression in this case is anonymous but assigned to a var for reference. This is different from a labeled function statement in the following ways:

it can't be hoisted (called before it's defined)

new someFunction().constructor.name === 'someFunction';//false instances don't get the var name for constructor.name because a reference to the function is assigned to the var but the var, not the function, is tied to the var name

In a labeled function statement:

```<code>//someFunction(); //works when uncommented
function someFunction(){ alert('yay'); }
</code>```

hoisting works

new someFunction().constructor.name === 'someFunction'; //true the name is tied directly to the function.

Generally speaking there's not really any great reason to do expression to var unless you want calls to fail if things get moved around or you're defining/assigning a method in one line. I actually find hoisting useful for organizing objects with internal func and method definitions at the bottom so I can get to the actual behavior of the object and do one-line public method definitions (by just assigning funcs to this. with the same name) all in one spot for ease of reference. You should always try to use labeled statements for constructors, IMO, so you can identify an object's 'type' via its constructor.

Body:
function expression:

//someFunction(); //wouldn't work when uncommented
var someFunction = function(){ alert('yay'); };

The func expression in this case is anonymous but assigned to a var for reference. This is different from a labeled function statement in the following ways:

it can't be hoisted (called before it's defined)

new someFunction().constructor.name === 'someFunction';//false instances don't get the var name for constructor.name because a reference to the function is assigned to the var but the var, not the function, is tied to the var name

In a labeled function statement:

//someFunction(); //works when uncommented
function someFunction(){ alert('yay'); }

hoisting works

new someFunction().constructor.name === 'someFunction'; //true the name is tied directly to the function.

Generally speaking there's not really any great reason to do expression to var unless you want calls to fail if things get moved around or you're defining/assigning a method in one line. I actually find hoisting useful for organizing objects with internal func and method definitions at the bottom so I can get to the actual behavior of the object and do one-line public method definitions (by just assigning funcs to this. with the same name) all in one spot for ease of reference. You should always try to use labeled statements for constructors, IMO, so you can identify an object's 'type' via its constructor.


答:
The main practical difference is hoisting. For example:

```<code>foo(); // alerts 'hello'
function foo() {alert('hello');}
</code>```

vs

```<code>foo(); // throws an error since foo is undefined
var foo = function() {alert('hello');}
</code>```

Also, this is undefined behavior

```<code>function foo(){
  if (true) {
    function bar(){}
  }
  bar();
}
</code>```

while this is ok.

```<code>function foo(){
  if (true) {
    var bar = function(){}
  }
  bar();
}
</code>```

Body:
The main practical difference is hoisting. For example:

foo(); // alerts 'hello'
function foo() {alert('hello');}

vs

foo(); // throws an error since foo is undefined
var foo = function() {alert('hello');}

Also, this is undefined behavior

function foo(){
  if (true) {
    function bar(){}
  }
  bar();
}

while this is ok.

function foo(){
  if (true) {
    var bar = function(){}
  }
  bar();
}


答:
Step one is of course to remove the "gotchas" from the code. Clear, concise, consistent code is easier to get into, work with, and debug.

Where do you start?

I ask the newcomer how they want to get into the codebase. Everyone learns differently. Some people like having little tasks to work with. Some like debugging existing code. Some want to see the code running to understand what it does. Some want to start at the entrypoint and just navigate around. Some want visio diagrams...  No set pattern is going to work best for everyone.

How do you cover unfamiliar technologies or patterns on the listener's part without taking all day?

I avoid them. Let them be black boxes until the newcomer asks about them. Then provide just enough information to get the jist of it, with the hint that they can learn more on their own time, or ask later when the general stuff is more well known.

Where do you tie in business logic vs. code-structure?

I try not to. It's almost always better for the newcomer to learn on their own so that it sits in their mind in a structure more natural to their way of thinking.

One thing to remember is to keep the instruction short. People tend to check out pretty quickly, so any more instruction at that point just doesn't 'stick'. Show them things for 15-60 minutes (different people have different attention spans) then take a 5-30 minute break for them to process it.

Title: How to introduce code to a colleague


问:
Best approach for writing a chess engine?
I'm a chess enthusiast and a programmer. I recently decided to start making a chess engine using my chess and programming knowledge. So here's my question:

What language (I'm familiar with Java, C++ and Python) and methodology should I adapt while writing a chess engine?

A little guidance would be much appreciated.

Edit:

So I decided to make it in JavaScript. I download this Chess UI from github and now I'm all set! My first step would be to write legal moves for it. So can anybody point me in the right direction? (I'm new to jQuery but have alot of programming experience).

P.S: I'm not trying to make a very efficient engine (I know its way too difficult), I just want to get familiar with the process and learn some new techniques along the way.

答:
The rules of chess itself are fairly simple.  You just need to be able to create a matrix (2-dimensional array) for the board, and find a way to encode the concepts of the pieces, the movement rules for each piece, validation that a move is legal, and conditions that signal the end of the game.  Nothing particularly hard about any of that.  You ought to use whichever language you're most familiar with.

Now if you want to make a chess-playing AI that will take the role of one of the players, that's where things get tricky.  But again, language choice isn't the biggest issue here; understanding the AI principles involved is.  That will be a much more  important factor.

(Having said that, this sort of decision-making can be extremely computationally intensive, and you'll probably want to use something that compiles to native code rather than a scripting language.  And C++ is a very bad choice, not because it's not well-suited to this problem but simply because it's a very bad language in general, and trying to implement complex stuff in it is a good way to code up all sorts of headaches for yourself.)