答:
Not a full answer, but you need to check out this pdf if you're going to learn Objective-C.

It's a really easy read if you like to read to learn languages, as opposed to looking at sample code or examples.  As long as you have an understanding of OOP then picking up Obj-C is smooth sailing.  The thing that really puts me off about learning iPhone dev is the use of Xcode, which is another story....

Apple Obj-C

Title: How much C/C++ knowledge is needed for Objective-C/iPhone development?

Body:
First, a little background. I'm a .Net developer (C#) and have over 5 years experience in both web development and desktop applications. I've been wanting to look into iPhone development for some time now, but for one reason or another always got side tracked. I finally have a potential project on the horizon, and I'm now going full steam ahead learning this stuff.

My question is this: I haven't done any C/C++ programming since my schooling days, I've been living in managed land ever since. How much knowledge if any is needed to be successful as an iOS developer? Obviously memory management is something that I'll have to be conscious about (although with iOS 5 there seems to be something called ARC which should make my life easier), but what else? I'm not just talking about the C API (for example, in order to get the sin of a number, I call the sin() function), that's what Google is for. I'm talking about fundamental C/C++ idioms that the average C# developer is unaware of.


问:
How do I choose a package format for Linux software distribution?
We have a Java-based application that, to date, we've been distributing as a tarball with instructions for deploying. It's mostly self-contained so deployment is fairly straight-forward:

Untar on the disk you'd like it to live on;

Make sure Java is in your path and a suitable distro and version;

Verify ownership and group on all the files

Start up the server processes with our start script

If the user wants to get in to start-on-boot stuff with SysV we have some written instructions and a template init file for it in our tarball.

We'd like to make this installation process a little more seamless; take care of the permissions and the init script deployment. We're also going to start bundling our own JRE with the application so that we're mostly free of external dependencies.

The question we're faced with now is: how do we pick a package format for distribution? Is RPM the standard? Can all package management tools deal with it now? Our clients primarily run RHEL and CentOS, but we do have some using SuSE and even Debian. If we can pick a distro-agnostic format we'd prefer that.

What about a self-extracting shell script? Something akin to how Java is distributed. If we're dependency-free would the self-extracting script be sufficient? What features or conveniences would we lose out on going with the script versus a proper package format meant for use by a package manager?

答:
RPM is more prevalent in the business friendly distros.  Debian and Ubuntu both use aptitude.  I like aptitude, they both work though.  They are not mutually exclusive, though.

Either should be able to verify your basic system facilities are present.  You could depend on specific versions of shared libraries, for instance.  I've never seen this sort of support in self extracting sorts of tools.

Self extracting is less common.  While easier to get a quick and dirty version out the door, you won't have a support system to lean on.  Think about how much money people pay for InstallShield. Entire companies make a living doing it.  It's unlikely that most organizations would spend the effort to do it right.  Suit types tend to think it's free and its a royal pain in the ass.

ContentLicense: CC BY-SA 3.0


问:
Is it more sensible to log exceptions in a catch-all or in a base exception class?
I'm in the process of refactoring a fairly large web app. One of the major issues is inconsistent error handling and I'm trying to come up with a sensible strategy.
I've created a custom error handler, via set_error_handler that essentially turns PHP errors in ErrorExceptions and a custom base exception class, that directly inherits from Exception.

On production I'm using a generic exception catch-all, via set_exception_handler, and I'm about to add exception logging* to the mix. My dilemma is where to do the actual logging, in the base exception class or in the catch-all.

I've thought of a couple of reasons to log it in the catch-all:

There are quite a few exceptions in the code that need to be converted to some appropriate child of the base exception class. Until that happens, not all exceptions will get logged.

It somehow feels more natural to do it in the catch-all, a base exception class shouldn't do more than being just that. (It might be a single responsibility principle thing, but it could just be a misguided feeling)

and one reason to log in the base exception class:

Currently the catch-all is only used on production. It would be easy to introduce it on our other environments (development, testing) but that would call for a few adjustments, as errors are handled differently per environment, as on production they are translated to 404/503 error pages.

Is there any acceptable practice for where to logging exceptions?

* Logging will involve writing to a text file at first, and it may evolve to sending mails for certain types of exceptions.

Some clarifications, prompted by @unholysampler's answer:

I'm facing a 2*10^6 sloc codebase, with a lot of third party stuff I have no control over, and some of the code I do have control over pre-dates exceptions in PHP. And there's also some crappy recent code, we are recovering from a long period of intense pressure where we virtually had to stop thinking and just hacked.

We are actively refactoring to address all the inconsistencies and introduce a sensible error handling approach, but that's going to take some time. I'm more interested in what to do until I reach the point where errors are handled appropriately. I'll probably ask another question on a sensible exception strategy at some point.

The main motivation behind logging is to get an email on my phone whenever something bad happens on production. I don't care if data dumps get huge, if they do I'll have a cron job deleting old ones every now and then.

答:
In short, the only time you should log the existence of an exception is when you are handling it.

When you throw an exception, it is because your code has reached a state where it can not proceed correctly. By throwing an exception, you are representing a specific message to your program about the error that occurred. You should not catch an exception until you are at a point where it can properly be handled.

The code you write as part of your main application should be aware of the types of exceptions that can be thrown and when they might be thrown. If you can't do anything productive with an exception, don't catch it. Do not log an exception until it is being handled. Only the handling code knows what the exception means in the context of the program flow and how to respond to it. Writing a log message here may make sense here. If you use a logging framework, you can set a log level for the message and potentially filter them. This works well for exceptions that can occur, but are not critical and can be recovered from cleanly.

Your exception catch-all, is your last ditch effort to keep your code from crashing an ugly death. If you have gotten this far, you log all the state and error information you can. Then you do your best to nicely tell the user that the program is crashing before everything stops. Your goal should be to never have this code executed.

Embedding logging into the base class does not follow the above guidelines. The base class doesn't know anything about the state of the code. (Having the stack trace doesn't count because you are not going to write code that makes decisions based on parsing it.) The base class can't do anything to indicate the severity or how the exception might be handled. You don't want huge data dumps and stack traces every time there is a simple exception that you can handle and recover from cleanly.


问:
Database design
I'm on the way developing an application which requires a kind of dynamic database,

So this is what I want,

This is the for reading the details of a class, the number of variables and methods will only be known at run-time, and I have to create a number of classes like this.

In the above scenario,how can I design a database (MySql) to store all these datas and retrieve them later?

答:
It would be very lengthy to give you a fully normalized db here. Hopefully this would get you started.

```<code>tblClasses
    pk Name
    AnyOtherDataYouwanttostore

tblAttributes
   fk ClassName <-> tblClasses.Name
   Name
   Visibility
   Type ...

tblFunctions
    fk ClassName <-> tblClasses.Name
    Name
    Visibility
    ReturnType ...
</code>```

Depending on your design, it may be better to use an Identity column for your primary key for tblClasses and then use that for your Foreign Key  in the other tables. It all depends on your datatypes and the rest of the data you need to store.

Title: Database design

Body:
It would be very lengthy to give you a fully normalized db here. Hopefully this would get you started.

tblClasses
    pk Name
    AnyOtherDataYouwanttostore

tblAttributes
   fk ClassName <-> tblClasses.Name
   Name
   Visibility
   Type ...

tblFunctions
    fk ClassName <-> tblClasses.Name
    Name
    Visibility
    ReturnType ...

Depending on your design, it may be better to use an Identity column for your primary key for tblClasses and then use that for your Foreign Key  in the other tables. It all depends on your datatypes and the rest of the data you need to store.


问:
Stuff every programmer needs while working
I've been tasked with creating a fun and relaxing environment, one thing I know that I want is ergonomic mice and keyboards, others have suggested exercise balls and bands.

What is it that every programmer needs while working? What might not be necessary but would be nice to have anyway?

Note: this question was asked previously, but has been recommended to be posted here. See this link for the previous responses: https://stackoverflow.com/questions/3911911/stuff-every-programmer-needs-while-working-closed

答:
Fast (i.e. 10000+rpm) disks!

Nothing frustrates me more than waiting for I/O, where I find my computer can't keep up with my thinking.

ContentLicense: CC BY-SA 2.5


问:
How to refactor code to some common code?
Background

I'm working on an ongoing C# project. I'm not a C# programmer, primarily a C++ programmer. So I was assigned basically easy and refactoring tasks.

The code is a mess. It's a huge project. As our customer demanded frequent releases with new features and bug fixes, all other developers were forced to take brute force approach while coding. The code is highly unmaintainable and all other developers agree with it.

I'm not here to debate whether they did it right. As I'm refactoring, I'm wondering if I'm doing it in the right way as my refactored code seems complex! Here is my task as simple example.

Problem

There are six classes: A, B, C, D, E and F. All of the classes have a function ExecJob(). All six implementations are very similar. Basically, at first A::ExecJob() was written. Then a slightly different version was required which was implemented in B::ExecJob() by copy-paste-modification of A::ExecJob(). When another slightly different version was required, C::ExecJob() was written and so on. All six implementations have some common code, then some different lines of code, then again some common code and so on. Here is a simple example of the implementations:

```<code>A::ExecJob()
{
    S1;
    S2;
    S3;
    S4;
    S5;
}

B::ExecJob()
{
    S1;
    S3;
    S4;
    S5;
}

C::ExecJob()
{
    S1;
    S3;
    S4;
}
</code>```

Where SN is a group of exact same statements.

To make them common, I've created another class and moved the common code in a function. Using parameter to control which group of statements should be executed:

```<code>Base::CommonTask(param)
{
    S1;
    if (param.s2) S2;
    S3;
    S4;
    if (param.s5) S5;
}

A::ExecJob() // A inherits Base
{
    param.s2 = true;
    param.s5 = true;
    CommonTask(param);
}

B::ExecJob() // B inherits Base
{
    param.s2 = false;
    param.s5 = true;
    CommonTask(param);
}

C::ExecJob() // C inherits Base
{
    param.s2 = false;
    param.s5 = false;
    CommonTask(param);
}
</code>```

Note that, this example only employs three classes and oversimplified statements. In practice, the CommonTask() function looks very complex with all those parameter checking and there are many more statements. Also, in real code, there are several CommonTask()-looking functions.

Though all the implementations are sharing common code and ExecJob() functions are looking cuter, there exists two problems that are bothering me:

For any change in CommonTask(), all six (and may be more in the future) features are needed to be tested.

CommonTask() is already complex. It will get more complex over time.

Am I doing it in the right way?

答:
You are actually doing the right thing.
I say this because :

If you need to change the code for a common task functionality, you don't need to change it in all 6 classes which would contain the code if you don't write it in a common class.

Number of lines of code will be decreased.


答:
First of all, if you're making a regular Linux package, there's no sane reason to bundle the JRE with it. Just declare a dependency on a JRE (I think this is possible for most of the major distros, somebody correct me if I'm wrong).

RPM is not the standard, but it's one of the main ones. That's the great thing about Linux - so many different standards to choose from. You should start by taking a survey of your users, and see what distros are most popular. You might be able to get away with an RPM for all Redhat-based systems, and a DEB for all Debian-based systems (this includes Ubuntu). Or you might have to sub-divide it further.

Title: How do I choose a package format for Linux software distribution?

Body:
We have a Java-based application that, to date, we've been distributing as a tarball with instructions for deploying. It's mostly self-contained so deployment is fairly straight-forward:

Untar on the disk you'd like it to live on;

Make sure Java is in your path and a suitable distro and version;

Verify ownership and group on all the files

Start up the server processes with our start script

If the user wants to get in to start-on-boot stuff with SysV we have some written instructions and a template init file for it in our tarball.

We'd like to make this installation process a little more seamless; take care of the permissions and the init script deployment. We're also going to start bundling our own JRE with the application so that we're mostly free of external dependencies.

The question we're faced with now is: how do we pick a package format for distribution? Is RPM the standard? Can all package management tools deal with it now? Our clients primarily run RHEL and CentOS, but we do have some using SuSE and even Debian. If we can pick a distro-agnostic format we'd prefer that.

What about a self-extracting shell script? Something akin to how Java is distributed. If we're dependency-free would the self-extracting script be sufficient? What features or conveniences would we lose out on going with the script versus a proper package format meant for use by a package manager?


问:
Is there a name for a testing method where you compare a set of very different designs?
"A/B testing" is defined as "a method of marketing testing by which a baseline control sample is compared to a variety of single-variable test samples in order to improve response rates".

The point here, of course, is to know which small single-variable changes are more optimal, with the goal of finding the local optimum.

However, one can also envision a somewhat related but different scenario for testing the response rate of major re-designs: take a baseline control design, take one or more completely different designs, and run test samples on those redesigns to compare response rates.

As a practical but contrived example, imagine testing a set of designs for the same website, one being minimalist "googly" design, one being cluttered "Amazony" design, and one being an artsy "designy" design (e.g. maximum use of design elements unlike Google but minimal simultaneously presented information, like Google but unlike Amazon)

Is there an official name for such testing?

It's definitely not A/B testing, since the main component of it (finding local optimum by testing single-variable small changes that can be attributed to response shift) is not present. This is more about trying to compare a set of local optimums, and compare to see which one works better as a global optimum. It's not a multivriable, A/B/N or any other such testing since you don't really have specific variables that can be attributed, just different designs.

答:
This is still A/B testing.

As you may know, amazon has been doing a major A/B test of exactly this kind on their website. Internally, they refer to it as an A/B test.

(My wife has had the newer, cleaner design for months while I still have their age-old, cluttered design.)


答:
Yes, you are absolutely in the right path!

In my experience, I noticed that when things are complicated, the changes happen in small steps. What you have done is the step 1 in the evolution process (or refactoring process). Here is step 2 and step 3:

Step 2

```<code>class Base {
  method ExecJob() {
    S1();
    S2();
    S3();
    S4();
    S5();
  }
  method S1() { //concrete implementation }
  method S3() { //concrete implementation }
  method S4() { //concrete implementation}
  abstract method S2();
  abstract method S5();
}

class A::Base {
  method S2() {//concrete implementation}
  method S5() {//concrete implementation}
}

class B::Base {
  method S2() { // empty implementation}
  method S5() {//concrete implementation}
}

class C::Base {
  method S2() { // empty implementation}
  method S5() { // empty implementation}
}
</code>```

This is the 'Template Design Pattern' and it is one step ahead in the refactoring process. If the base class changes, the subclasses (A,B,C) don't need to get affected. You can add new subclasses relatively easily. However, right away from the picture above you can see that
the abstraction is broken. The need for 'empty implementation' is a good indicator; it shows that there is something wrong with your abstraction. It might have been an acceptable solution for short-term, but there seems to be a better one.

Step 3

```<code>interface JobExecuter {
  void executeJob();
}
class A::JobExecuter {
  void executeJob(){
     helper = new Helper();
     helper->S1();
     helper->S2();
     helper->S3();
     helper->S4();
     helper->S5();
  }
}

class B::JobExecuter {
  void executeJob(){
     helper = new Helper();
     helper->S1();
     helper->S3();
     helper->S4();
     helper->S5();
  }
}

class C::JobExecuter {
  void executeJob(){
     helper = new Helper();
     helper->S1();
     helper->S3();
     helper->S4();
  }
}

class Base{
   void ExecJob(JobExecuter executer){
       executer->executeJob();
   }
}

class Helper{
    void S1(){//Implementation}
    void S2(){//Implementation}
    void S3(){//Implementation}
    void S4(){//Implementation}
    void S5(){//Implementation}
}
</code>```

This is the 'Strategy Design Pattern' and seems as a good fit for your case. There are different strategies to execute the job and each class (A,B,C) implements it differently.

I am sure there is a step 4 or step 5 in this process or a lot better refactoring approaches. However, this one will let you eliminate duplicate code and make sure that the changes are localized.

Title: How to refactor code to some common code?

Body:
Background

I'm working on an ongoing C# project. I'm not a C# programmer, primarily a C++ programmer. So I was assigned basically easy and refactoring tasks.

The code is a mess. It's a huge project. As our customer demanded frequent releases with new features and bug fixes, all other developers were forced to take brute force approach while coding. The code is highly unmaintainable and all other developers agree with it.

I'm not here to debate whether they did it right. As I'm refactoring, I'm wondering if I'm doing it in the right way as my refactored code seems complex! Here is my task as simple example.

Problem

There are six classes: A, B, C, D, E and F. All of the classes have a function ExecJob(). All six implementations are very similar. Basically, at first A::ExecJob() was written. Then a slightly different version was required which was implemented in B::ExecJob() by copy-paste-modification of A::ExecJob(). When another slightly different version was required, C::ExecJob() was written and so on. All six implementations have some common code, then some different lines of code, then again some common code and so on. Here is a simple example of the implementations:

```<code>A::ExecJob()
{
    S1;
    S2;
    S3;
    S4;
    S5;
}

B::ExecJob()
{
    S1;
    S3;
    S4;
    S5;
}

C::ExecJob()
{
    S1;
    S3;
    S4;
}
</code>```

Where SN is a group of exact same statements.

To make them common, I've created another class and moved the common code in a function. Using parameter to control which group of statements should be executed:

```<code>Base::CommonTask(param)
{
    S1;
    if (param.s2) S2;
    S3;
    S4;
    if (param.s5) S5;
}

A::ExecJob() // A inherits Base
{
    param.s2 = true;
    param.s5 = true;
    CommonTask(param);
}

B::ExecJob() // B inherits Base
{
    param.s2 = false;
    param.s5 = true;
    CommonTask(param);
}

C::ExecJob() // C inherits Base
{
    param.s2 = false;
    param.s5 = false;
    CommonTask(param);
}
</code>```

Note that, this example only employs three classes and oversimplified statements. In practice, the CommonTask() function looks very complex with all those parameter checking and there are many more statements. Also, in real code, there are several CommonTask()-looking functions.

Though all the implementations are sharing common code and ExecJob() functions are looking cuter, there exists two problems that are bothering me:

For any change in CommonTask(), all six (and may be more in the future) features are needed to be tested.

CommonTask() is already complex. It will get more complex over time.

Am I doing it in the right way?

Body:
Yes, you are absolutely in the right path!

In my experience, I noticed that when things are complicated, the changes happen in small steps. What you have done is the step 1 in the evolution process (or refactoring process). Here is step 2 and step 3:

Step 2

class Base {
  method ExecJob() {
    S1();
    S2();
    S3();
    S4();
    S5();
  }
  method S1() { //concrete implementation }
  method S3() { //concrete implementation }
  method S4() { //concrete implementation}
  abstract method S2();
  abstract method S5();
}

class A::Base {
  method S2() {//concrete implementation}
  method S5() {//concrete implementation}
}

class B::Base {
  method S2() { // empty implementation}
  method S5() {//concrete implementation}
}

class C::Base {
  method S2() { // empty implementation}
  method S5() { // empty implementation}
}

This is the 'Template Design Pattern' and it is one step ahead in the refactoring process. If the base class changes, the subclasses (A,B,C) don't need to get affected. You can add new subclasses relatively easily. However, right away from the picture above you can see that
the abstraction is broken. The need for 'empty implementation' is a good indicator; it shows that there is something wrong with your abstraction. It might have been an acceptable solution for short-term, but there seems to be a better one.

Step 3

interface JobExecuter {
  void executeJob();
}
class A::JobExecuter {
  void executeJob(){
     helper = new Helper();
     helper->S1();
     helper->S2();
     helper->S3();
     helper->S4();
     helper->S5();
  }
}

class B::JobExecuter {
  void executeJob(){
     helper = new Helper();
     helper->S1();
     helper->S3();
     helper->S4();
     helper->S5();
  }
}

class C::JobExecuter {
  void executeJob(){
     helper = new Helper();
     helper->S1();
     helper->S3();
     helper->S4();
  }
}

class Base{
   void ExecJob(JobExecuter executer){
       executer->executeJob();
   }
}

class Helper{
    void S1(){//Implementation}
    void S2(){//Implementation}
    void S3(){//Implementation}
    void S4(){//Implementation}
    void S5(){//Implementation}
}

This is the 'Strategy Design Pattern' and seems as a good fit for your case. There are different strategies to execute the job and each class (A,B,C) implements it differently.

I am sure there is a step 4 or step 5 in this process or a lot better refactoring approaches. However, this one will let you eliminate duplicate code and make sure that the changes are localized.


问:
When to go Fluent in C#?
In many respects I really like the idea of Fluent interfaces, but with all of the modern features of C# (initializers, lambdas, named parameters) I find myself thinking, "is it worth it?", and "Is this the right pattern to use?". Could anyone give me, if not an accepted practice, at least their own experience or decision matrix for when to use the Fluent pattern?

Conclusion:

Some good rules of thumb from the answers so far:

Fluent interfaces help greatly when you have more actions than setters, since calls benefit more from the context pass-through.

Fluent interfaces should be thought of as a layer over top of an api, not the sole means of use.

The modern features such as lambdas, initializers, and named parameters, can work hand-in-hand to make a fluent interface even more friendly.

Here is an example of what I mean by the modern features making it feel less needed. Take for example a (perhaps poor example) Fluent interface that allows me to create an Employee like:

```<code>Employees.CreateNew().WithFirstName("Peter")
                     .WithLastName("Gibbons")
                     .WithManager()
                          .WithFirstName("Bill")
                          .WithLastName("Lumbergh")
                          .WithTitle("Manager")
                          .WithDepartment("Y2K");
</code>```

Could easily be written with initializers like:

```<code>Employees.Add(new Employee()
              {
                  FirstName = "Peter",
                  LastName = "Gibbons",
                  Manager = new Employee()
                            {
                                 FirstName = "Bill",
                                 LastName = "Lumbergh",
                                 Title = "Manager",
                                 Department = "Y2K"
                            }
              });
</code>```

I could also have used named parameters in the constructors in this example.

答:
Fluent interfaces are very powerful features to provide within the context of your code, when don with the "right" reasoning.

If your aim is to simply create massive one-line code chains as a kind of pseudo-black-box, then you're probably barking up the wrong tree.  If on the other hand you are using it to add value to your API interface by providing a means to chain method calls and improve code readability, then with a lot of good planning and effort I think the effort is worth it.

I'd avoid following what seems to becoming a common "pattern" when creating fluent interfaces, where you name all of your fluent methods "with"-something, as it robs a potentially good API interface of its context, and therefore its intrinsic value.

The key is to think of the fluent syntax as a specific implementation of a Domain-specific language.  As a really good example of what I'm talking about, have a look at StoryQ, which employs fluency as a means to express a DSL in a very valuable and flexible manner.

OwnerDisplayName: ach

Title: When to go Fluent in C#?

ContentLicense: CC BY-SA 4.0


答:
You see this sort of code sharing a lot in with event driven design (.NET especially).  The most maintainable way is to keep your shared behavior in as small chunks as possible.

Let the high level code reuse a bunch of small methods, leave the high level code out of the shared base.

You will have a lot of boiler plate in your leaf/concrete implementations.  Don't panic, it's ok.  All that code is direct, easy to understand.  You'll have to rearrange it occasionally when stuff breaks, but it will be easy to change.

You'll see a lot of patterns in the high level code.  Sometimes they are real, most of the time they aren't.  The "configurations" of the five parameters up there look similar, but they aren't.  They are three entirely different strategies.

Also want to note that you can do all this with composition and never worry about inheritance.  You'll have less coupling.


问:
Would you use UML if it kept stakeholders from requesting changes frequently?
As much as programmers hate to document their code/system and draw UML (especially, Sequencing, Activity and State machine diagrams) or other diagramming notation, would you agree to do it if it kept managers from requesting a "minor change" every couple of weeks?

IOW, would you put together visual models to document the system if it helped you demonstrate to managers what the effect of changes are and why it takes so long to implement them?

(Edited to help programmers understand what type of answer I'm looking for.)

2nd edit: Restating my question again, "Would you be willing to use some diagramming notation, against your better nature as a programmer, if it helped you manage change requests?"

This question isn't asking if there might be something wrong with the process. It's a given that there's something wrong with the process. Would you be willing to do more work to improve it?

答:
Your problem is a lack of communication between you and your managers/stakeholders.

They don't understand the problems that making frequent changes can cause - even if you have an agile process in place.

But equally the developers don't understand the need that the program is designed to solve or the business process as well as you should.

Why do I say this?

If the managers were familiar with the development process then they'd know when was the appropriate time to request changes - before the start of the next sprint, or when the design document for the next phase was being written etc.

If the developers understood the problem better then the product would be closer to the needs of the stakeholders.

You need to address the communication issue and put in place procedures to manage the change - because change will happen.

Hiding behind UML diagrams (or specifications, or even story cards) isn't going to solve the problem.


答:
You may want to look into MongoDB.  Its significantly different than MySQL as it is in the NoSQL group but seems like it might be a good fit for what you need.  You can store the dynamic aspects in one table in an array which is something you can't do in a MySQL setup.  If however you need/want to stick with the MySQL database then the appropriate method is to split the data between tables as suggested by Jonathan Henson.

FYI the MongoDB Structure would be something like the following:

```<code>Classes:
{
  Name : NameValue,
  Attributes : {
      0 : {
        AttName : AttNameValue0,
        AttVisibility : AttVisibilityValue0,
        AttType : AttTypeValue0
        },
      1 : {
        AttName : AttNameValue1,
        AttVisibility : AttVisibilityValue1,
        AttType : AttTypeValue1
        },
      2 : ...
    },
  Functions: {
      0 : {
        FuncName : FuncNameValue0,
        FuncVisibility : FuncVisibilityValue0,
        FuncReturnType : FuncReturnTypeValue0
        },
      1 : {
        FuncName : FuncNameValue1,
        FuncVisibility : FuncVisibilityValue1,
        FuncReturnType : FuncReturnTypeValue1
        },
      2 : ...
    }
  ...
}
</code>```

Title: Database design

Body:
I'm on the way developing an application which requires a kind of dynamic database,

So this is what I want,

This is the for reading the details of a class, the number of variables and methods will only be known at run-time, and I have to create a number of classes like this.

In the above scenario,how can I design a database (MySql) to store all these datas and retrieve them later?

Body:
You may want to look into MongoDB.  Its significantly different than MySQL as it is in the NoSQL group but seems like it might be a good fit for what you need.  You can store the dynamic aspects in one table in an array which is something you can't do in a MySQL setup.  If however you need/want to stick with the MySQL database then the appropriate method is to split the data between tables as suggested by Jonathan Henson.

FYI the MongoDB Structure would be something like the following:

Classes:
{
  Name : NameValue,
  Attributes : {
      0 : {
        AttName : AttNameValue0,
        AttVisibility : AttVisibilityValue0,
        AttType : AttTypeValue0
        },
      1 : {
        AttName : AttNameValue1,
        AttVisibility : AttVisibilityValue1,
        AttType : AttTypeValue1
        },
      2 : ...
    },
  Functions: {
      0 : {
        FuncName : FuncNameValue0,
        FuncVisibility : FuncVisibilityValue0,
        FuncReturnType : FuncReturnTypeValue0
        },
      1 : {
        FuncName : FuncNameValue1,
        FuncVisibility : FuncVisibilityValue1,
        FuncReturnType : FuncReturnTypeValue1
        },
      2 : ...
    }
  ...
}


答:
If i was you i will probably add 1 more step at the beginning: a UML-based study.

Refactoring the code merging all the common parts together isn't always the best move, sounds more like a temporary solution than a good approach.

Draws a UML scheme, keep the things simple but effective, keep in mind some basic concepts about your project like "what is supposed to do this software?" "what is the best way to keep this piece of software abstract, modular, extensible, ... etc etc ?" "how i can implement the encapsulation at its best?"

I'm just saying this: do not care about the code right now, you only have to care about the logic, when you have a clear logic in mind all the rest can become a really easy task, in the end all the this kind of problems that you are facing is merely caused by a bad logic.


问:
Are there studies about the disadvantages of using issue tracking systems?
I don't like issue tracking systems because:

It takes too much time to describe issues in it. This discourage its usage.

You create a place to keep your bugs. And if there is a place for them, people usually don't care too much about fixing a bug cause they can put it there so that someday someone can fix it (or not).

With time, the bug lists gets so long that nobody can deal with it anymore, taking up a lot of our time.

I prefer handling issues using post-its on a white board, face-to-face conversations and killing important bugs as soon as they appear. I don't care too much to keep track of bug history because I don't think that it is worth the overhead.

Am I alone here? Are there studies (book/article/whatever) about the disadvantages (or great advantages) of using issue tracking systems?

答:
killing important bugs as soon as they appear

It sounds like you're breaking into the open door here. Important bugs get "killed" as soon as possible no matter if you use issue tracker or not.

Oh and part "as they appear" is quite slippery BTW. In one project we had an important bug that threatened to throw the whole product out of business (what could be more important?). It was very complicated (architecture error) and we knew it will take long to fix it. Customers kindly agreed to give us a year to fix (before dropping our product) and we did it in about a year.

As for issue trackers, I've been using these for almost ten years and as a rule, all programmers around me spent quite little time with tracker (note I am talking about programmers; managers are different story). I have seen cases (rarely) when it was not so - in all these cases something was severely broken.

Regarding studies on face-to-face conversations vs issue tracking, again it feels like you're breaking into the open door here. Issue tracking is a typical written communication; there are plenty research showing that to discuss things, face2face communication is much more efficient than over the phone which is in turn much more efficient than written.

Actually given that you ask about f2f it feels like you're (mis)using tracker to discuss things - this is not its purpose. To figure its intended use, just spell its name slowly and clearly: issue tracking system.

the bug lists gets so long

In my experience, above is an advantage not a problem.

With long bug list developers can set up a queue and plan fixes far ahead. This is as productive as it gets; to me this is basically a nirvana when I have such a queue to work with. First bug - fix - done, second bug - fix - done, next bug - fix - done etc etc. No stupid interruptions, no painful distractions with oh-so-efficient f2f conversations, pure flow.

I recall only one case when long bug lists have been a problem. It happened when some idiot at higher management decided on a policy that forced developers to pick next bug from a pile of 50-100 almost daily. What a waste. It took us a few months of pain until we figured how to escalate this over his head and get it fixed.

Some time after we managed to establish convenient work flow we discovered that our "endless backlog" magically got empty.


答:
First, you should make sure that inheritance is really the right tool here for the job - only because you need a common place for functions used by your classes A to F does not mean that a common base class is the right thing here - sometimes a separate helper class does the job better. It may be, it may be not. That depends on having a "is-a" relationship between A to F and your common base class, impossible to say from artificial names A-F. Here you find a blog post dealing with this topic.

Let's assume you decide that the common base class is the right thing in your case. Then
the second thing I would do is to make sure your code fragments S1 to S5 are each implemented in a separate methods S1() to S5() of your base class. Afterwards the "ExecJob" functions should look like this:

```<code>A::ExecJob()
{
    S1();
    S2();
    S3();
    S4();
    S5();
}

B::ExecJob()
{
    S1();
    S3();
    S4();
    S5();
}

C::ExecJob()
{
    S1();
    S3();
    S4();
}
</code>```

As you see now, since S1 to S5 are just method calls, no code blocks any more, the code duplication has been almost completely removed, and you don't need any parameter checking any more, avoiding the problem of increasing complexity you might get otherwise.

Finally, but only as a third step(!), you might think about combining all those ExecJob methods into one of your base class, where the execution of those parts may be controlled by parameters, just the way you suggested it, or by using template method pattern. You have to decide yourself if that's worth the effort in your case, based on the real code.

But IMHO the basic technique to break down big methods into small methods is much, much more important for avoiding code duplication than applying patterns.

Body:
First, you should make sure that inheritance is really the right tool here for the job - only because you need a common place for functions used by your classes A to F does not mean that a common base class is the right thing here - sometimes a separate helper class does the job better. It may be, it may be not. That depends on having a "is-a" relationship between A to F and your common base class, impossible to say from artificial names A-F. Here you find a blog post dealing with this topic.

Let's assume you decide that the common base class is the right thing in your case. Then
the second thing I would do is to make sure your code fragments S1 to S5 are each implemented in a separate methods S1() to S5() of your base class. Afterwards the "ExecJob" functions should look like this:

A::ExecJob()
{
    S1();
    S2();
    S3();
    S4();
    S5();
}

B::ExecJob()
{
    S1();
    S3();
    S4();
    S5();
}

C::ExecJob()
{
    S1();
    S3();
    S4();
}

As you see now, since S1 to S5 are just method calls, no code blocks any more, the code duplication has been almost completely removed, and you don't need any parameter checking any more, avoiding the problem of increasing complexity you might get otherwise.

Finally, but only as a third step(!), you might think about combining all those ExecJob methods into one of your base class, where the execution of those parts may be controlled by parameters, just the way you suggested it, or by using template method pattern. You have to decide yourself if that's worth the effort in your case, based on the real code.

But IMHO the basic technique to break down big methods into small methods is much, much more important for avoiding code duplication than applying patterns.


答:
The very first step, no matter where this is going, should be breaking the apparently large method A::ExecJob into smaller pieces.

Therefore, instead of

```<code>A::ExecJob()
{
    S1; // many lines of code
    S2; // many lines of code
    S3; // many lines of code
    S4; // many lines of code
    S5; // many lines of code
}
</code>```

you get

```<code>A::ExecJob()
{
    S1();
    S2();
    S3();
    S4();
    S5();
}

A:S1()
{
   // many lines of code
}

A:S2()
{
   // many lines of code
}

A:S3()
{
   // many lines of code
}

A:S4()
{
   // many lines of code
}

A:S5()
{
   // many lines of code
}
</code>```

From here on, there are many possible ways to go. My take on it:
Make A the base class of your class hierachy and ExecJob virtual and it becomes easy to create B, C, ... without too much copy-paste - just replace ExecJob (now a five-liner) with a modified version.

```<code>B::ExecJob()
{
    S1();
    S3();
    S4();
    S5();
}
</code>```

But why have so many classes at all? Maybe you can replace them all with a single class that has a constructor which can be told which actions are necessary in ExecJob.

Body:
The very first step, no matter where this is going, should be breaking the apparently large method A::ExecJob into smaller pieces.

Therefore, instead of

A::ExecJob()
{
    S1; // many lines of code
    S2; // many lines of code
    S3; // many lines of code
    S4; // many lines of code
    S5; // many lines of code
}

you get

A::ExecJob()
{
    S1();
    S2();
    S3();
    S4();
    S5();
}

A:S1()
{
   // many lines of code
}

A:S2()
{
   // many lines of code
}

A:S3()
{
   // many lines of code
}

A:S4()
{
   // many lines of code
}

A:S5()
{
   // many lines of code
}

From here on, there are many possible ways to go. My take on it:
Make A the base class of your class hierachy and ExecJob virtual and it becomes easy to create B, C, ... without too much copy-paste - just replace ExecJob (now a five-liner) with a modified version.

B::ExecJob()
{
    S1();
    S3();
    S4();
    S5();
}

But why have so many classes at all? Maybe you can replace them all with a single class that has a constructor which can be told which actions are necessary in ExecJob.


问:
When does the "Do One Thing" paradigm become harmful?
For the sake of argument here's a sample function that prints contents of a given file line-by-line.

Version 1:

```<code>void printFile(const string & filePath) {
  fstream file(filePath, ios::in);
  string line;
  while (std::getline(file, line)) {
    cout << line << endl;
  }
}
</code>```

I know it is recommended that functions do one thing at one level of abstraction. To me, though code above does pretty much one thing and is fairly atomic.

Some books (such as Robert C. Martin's Clean Code) seem to suggest breaking the above code into separate functions.

Version 2:

```<code>void printFile(const string & filePath) {
  fstream file(filePath, ios::in);
  printLines(file);
}

void printLines(fstream & file) {
  string line;
  while (std::getline(file, line)) {
    printLine(line);
  }
}

void printLine(const string & line) {
  cout << line << endl;
}
</code>```

I understand what they want to achieve (open file / read lines / print line), but isn't it a bit of overkill?

The original version is simple and in some sense already does one thing - prints a file.

The second version will lead to a large number of really small functions which may be far less legible than the first version.

Wouldn't it be, in this case, better to have the code at one place?

At which point does the "Do One Thing" paradigm become harmful?

答:
IMO it becomes harmful when it goes that far that a function hardly does anything at all but delegate work to another function, because that's a sign that it is no longer an abstraction of anything and the mindset that leads to such functions is always in danger of doing worse things...

From the original post

```<code>void printLine(const string & line) {
  cout << line << endl;
}
</code>```

If you are pedantic enough, you might notice that printLine still does two things: writing the line to cout and adding a "end line" character. Some people might want to handle that by creating new functions:

```<code>void printLine(const string & line) {
  reallyPrintLine(line);
  addEndLine();
}

void reallyPrintLine(const string & line) {
  cout << line;
}

void addEndLine() {
  cout << endl;
}
</code>```

Oh no, now we have made the problem even worse! Now it's even OBVIOUS that printLine does TWO things!!!1! It doesn't make much stupidity to create the most absurd "work-arounds" one can imagine just to get rid of that inevitable problem that printing a line consists of printing the line itself and adding an end-of-line character.

```<code>void printLine(const string & line) {
  for (int i=0; i<2; i++)
    reallyPrintLine(line, i);
}

void reallyPrintLine(const string & line, int action) {
  cout << (action==0?line:endl);
}
</code>```

OwnerDisplayName: Petr

Body:
IMO it becomes harmful when it goes that far that a function hardly does anything at all but delegate work to another function, because that's a sign that it is no longer an abstraction of anything and the mindset that leads to such functions is always in danger of doing worse things...

From the original post

void printLine(const string & line) {
  cout << line << endl;
}

If you are pedantic enough, you might notice that printLine still does two things: writing the line to cout and adding a "end line" character. Some people might want to handle that by creating new functions:

void printLine(const string & line) {
  reallyPrintLine(line);
  addEndLine();
}

void reallyPrintLine(const string & line) {
  cout << line;
}

void addEndLine() {
  cout << endl;
}

Oh no, now we have made the problem even worse! Now it's even OBVIOUS that printLine does TWO things!!!1! It doesn't make much stupidity to create the most absurd "work-arounds" one can imagine just to get rid of that inevitable problem that printing a line consists of printing the line itself and adding an end-of-line character.

void printLine(const string & line) {
  for (int i=0; i<2; i++)
    reallyPrintLine(line, i);
}

void reallyPrintLine(const string & line, int action) {
  cout << (action==0?line:endl);
}


答:
If your language/runtime does not easily let you determine the source of the exception, there's a case for logging it at the throw. C++ and some JS engines do not expose the file+line or call stack of the exception by the time you've caught it / but this information is available at the time you construct the exception. </p>

<p>Our solution was to provide a mechanism that used runtime configuration to enable logging the type of the exception along with a cheap-stack when trying to diagnose these issues. </p>

Title: Is it more sensible to log exceptions in a catch-all or in a base exception class?

Body:
I'm in the process of refactoring a fairly large web app. One of the major issues is inconsistent error handling and I'm trying to come up with a sensible strategy.
I've created a custom error handler, via set_error_handler that essentially turns PHP errors in ErrorExceptions and a custom base exception class, that directly inherits from Exception.

On production I'm using a generic exception catch-all, via set_exception_handler, and I'm about to add exception logging* to the mix. My dilemma is where to do the actual logging, in the base exception class or in the catch-all.

I've thought of a couple of reasons to log it in the catch-all:

There are quite a few exceptions in the code that need to be converted to some appropriate child of the base exception class. Until that happens, not all exceptions will get logged.

It somehow feels more natural to do it in the catch-all, a base exception class shouldn't do more than being just that. (It might be a single responsibility principle thing, but it could just be a misguided feeling)

and one reason to log in the base exception class:

Currently the catch-all is only used on production. It would be easy to introduce it on our other environments (development, testing) but that would call for a few adjustments, as errors are handled differently per environment, as on production they are translated to 404/503 error pages.

Is there any acceptable practice for where to logging exceptions?

* Logging will involve writing to a text file at first, and it may evolve to sending mails for certain types of exceptions.

Some clarifications, prompted by @unholysampler's answer:

I'm facing a 2*10^6 sloc codebase, with a lot of third party stuff I have no control over, and some of the code I do have control over pre-dates exceptions in PHP. And there's also some crappy recent code, we are recovering from a long period of intense pressure where we virtually had to stop thinking and just hacked.

We are actively refactoring to address all the inconsistencies and introduce a sensible error handling approach, but that's going to take some time. I'm more interested in what to do until I reach the point where errors are handled appropriately. I'll probably ask another question on a sensible exception strategy at some point.

The main motivation behind logging is to get an email on my phone whenever something bad happens on production. I don't care if data dumps get huge, if they do I'll have a cron job deleting old ones every now and then.

Body:
If your language/runtime does not easily let you determine the source of the exception, there's a case for logging it at the throw. C++ and some JS engines do not expose the file+line or call stack of the exception by the time you've caught it / but this information is available at the time you construct the exception.

Our solution was to provide a mechanism that used runtime configuration to enable logging the type of the exception along with a cheap-stack when trying to diagnose these issues.


问:
How to document and teach others "optimized beyond recognition" computationally intensive code?
Occasionally there is the 1% of code that is computationally intensive enough that needs the heaviest kind of low-level optimization. Examples are video processing, image processing, and all kinds of signal processing, in general.

The goals are to document, and to teach the optimization techniques, so that the code does not become unmaintainable and prone to removal by newer developers. (*)

(*) Notwithstanding the possibility that the particular optimization is completely useless in some unforeseeable future CPUs, such that the code will be deleted anyway.

Considering that software offerings (commercial or open-source) retain their competitive advantage by having the fastest code and making use of the newest CPU architecture, software writers often need to tweak their code to make it run faster while getting the same output for a certain task, whlist tolerating a small amount of rounding errors.

Typically, a software writer can keep many versions of a function as a documentation of each optimization / algorithm rewrite that takes place. How does one make these versions available for others to study their optimization techniques?

Related:

Clean readable code vs fast hard to read code. When to cross the line?

答:
I believe this to be best solved through comprehensive commenting of the code, to the point where each significant block of code has explanatory commenting beforehand.

The comments should include citations to the specifications or hardware reference material.

Use industry-wide terminology and algorithm names where appropriate - e.g. 'architecture X generates CPU traps for unaligned reads, so this Duff's Device fills to the next alignment boundary'.

I would use in-your-face variable naming to ensure no misunderstanding of what is going on. Not Hungarian, but things like 'stride' to describe the distance in bytes between two vertical pixels.

I would also supplement this with a short, humanly readable document which has high-level diagrams and block design.


答:
Extract methods when you feel the need for a comment to explain things.

Write methods that either only do what their name says in an obvious way, or tell a story by calling cleverly named methods.

Title: When does the "Do One Thing" paradigm become harmful?

Body:
For the sake of argument here's a sample function that prints contents of a given file line-by-line.

Version 1:

```<code>void printFile(const string & filePath) {
  fstream file(filePath, ios::in);
  string line;
  while (std::getline(file, line)) {
    cout << line << endl;
  }
}
</code>```

I know it is recommended that functions do one thing at one level of abstraction. To me, though code above does pretty much one thing and is fairly atomic.

Some books (such as Robert C. Martin's Clean Code) seem to suggest breaking the above code into separate functions.

Version 2:

```<code>void printFile(const string & filePath) {
  fstream file(filePath, ios::in);
  printLines(file);
}

void printLines(fstream & file) {
  string line;
  while (std::getline(file, line)) {
    printLine(line);
  }
}

void printLine(const string & line) {
  cout << line << endl;
}
</code>```

I understand what they want to achieve (open file / read lines / print line), but isn't it a bit of overkill?

The original version is simple and in some sense already does one thing - prints a file.

The second version will lead to a large number of really small functions which may be far less legible than the first version.

Wouldn't it be, in this case, better to have the code at one place?

At which point does the "Do One Thing" paradigm become harmful?


问:
Infix vs Prefix Notation - Which do you prefer?
I have been learning Clojure and looking at Scheme and CL which introduced me to the world of prefix notation. At first I didn't like it but it is still starting to grow on me. To be honest though, there are still long calculations that are difficult for me to understand but I think that is an issue of me needing more exposure/practice and I'll get it.

But that leads me to the question: Which type of notation do you prefer and why?

答:
Postfix. It is clearly the most commonly used in procedural languages and object oriented languages.

Sequential code is postfix notation:

```
  do x; do y; do z;
```

OO code is postfix too:

```
   a.x.y
```

Most OO and procedural languages used both these conventions heavily mixed with a bit of infix and maybe some prefix to lighten the cognitive load an increase pattern recognition.

Even functional languages use postfix like format commonly:

```
   let x = g r in
   let y = f x in
   ..
```

as a way to make the less comprehensible prefix version:

```
  let y = f (g r) in
```

easier to read by factorisation (please imagine a longer more nasty chain of applications:)

Body:
Postfix. It is clearly the most commonly used in procedural languages and object oriented languages.

Sequential code is postfix notation:

  do x; do y; do z;

OO code is postfix too:

   a.x.y

Most OO and procedural languages used both these conventions heavily mixed with a bit of infix and maybe some prefix to lighten the cognitive load an increase pattern recognition.

Even functional languages use postfix like format commonly:

   let x = g r in
   let y = f x in
   ..

as a way to make the less comprehensible prefix version:

  let y = f (g r) in

easier to read by factorisation (please imagine a longer more nasty chain of applications:)


问:
Why are part-time jobs in programming an anomaly?
I've recently quit my full time developing job at mega-corp, and I decided that I'll look for a part time job. Since then I've talked to half a dozen potential employers, and every one of them had the same reaction when I said the magic words "part-time" - they all closed up and became suspicious. Now, I understand that it might just be me, so as control I asked every one of them what if I were willing to work full time, and they all said I would probably get an offer.

My question is two fold:

Why, as an employer, would you give up a competent, even great, developer, simply because he wants to work 3 days a week and not 5?

How do I sell the story of part time job better? I usually just list my reasons which are that I prefer that balance currently in my life and that I want to work on my own projects, but it leaves them even more suspicious - am I going to start something myself and quit? Am I just lazy?

答:
Asking for a part-time job without further explanation looks like you don't really want to work for them.

It may looks like you will use them until you don't need them anymore.

Here are few issues your employer may see in that proposal:

For the same amount of "work", you will duplicate their problems: 2x communication, 2x administative work (sick days, holidays, ...), 2x more risk to have to start the hiring process again...

If your colleagues or your boss(es) really need an information from you, the probability to be unable to reach you is 0.5.

Your colleague may not understand your particular situation as well.

Working like that will be really feasible if the employer is actively looking for a part-time programmer. One of the most common reason is that they can't afford one full programmer. This may give you hints to make a list of potential employers, such as small businesses not specifically working in the software field.


问:
Are Nassi-Shneiderman diagrams actually used?
I learned about them in a Structured Programming course, but never saw them used thereafter either at the analysis phase or for documentation purposes. Not even for highly structured languages like Pascal (Delphi).

Does any of you actually use Nassi-Shneiderman diagrams? If yes, what tools do you use to create/maintain them?

edit:

Or have you never heard of them?

答: I thought they were cool when I came across the notation in the early 80s. But it's so close to normal code, and cumbersome to maintain both the diagrams and the code that I decided just using indented code was close enough for my taste.</p>


答:
There's lots of things that may factor in, such as the longer the time between working, the more you've forgotten and the longer it takes to figure out where you left off, reducing the productivity.

There's also the widespread (and largely justified) view that great developers want to develop - that the issue is preventing them from burning themselves out, and that developers who want to work fewer hours are not great almost by definition.

Probably the key factor, though, is that you're basically asking employers to pay the full cost of bringing you up to speed etc, despite only offering around 60% (at best) of the payoff. Would you pay the full price for a 60% share of the ownership of a computer (excluding Apple owners).

Of course in real life it's a more complex formula than that, as productivity depends on a lot of factors and is never constant through all your working hours unless its constantly zero - but the complexity of that formula argues against at least as much as for your position. For example, less intensive learning is usually slower learning - bigger gaps mean more is forgotten between times.

Title: Why are part-time jobs in programming an anomaly?

Body:
I've recently quit my full time developing job at mega-corp, and I decided that I'll look for a part time job. Since then I've talked to half a dozen potential employers, and every one of them had the same reaction when I said the magic words "part-time" - they all closed up and became suspicious. Now, I understand that it might just be me, so as control I asked every one of them what if I were willing to work full time, and they all said I would probably get an offer.

My question is two fold:

Why, as an employer, would you give up a competent, even great, developer, simply because he wants to work 3 days a week and not 5?

How do I sell the story of part time job better? I usually just list my reasons which are that I prefer that balance currently in my life and that I want to work on my own projects, but it leaves them even more suspicious - am I going to start something myself and quit? Am I just lazy?


问:
synchronization web service methodologies or papers
I am building a web service (PHP+JSON) to sync with my iphone app. The main goals are:

Backup

Provide a web view for printing / sorting, manipulating.

allow a group sync up and down.

I am aware of the logic problems with all of these items, Ie. if one person deletes something, do you persist this change to other users, collisions, etc.

I am looking for just any book or scholarly work, or even words of wisdom to address common issues.

when to detect changes of data with hashes, vs modified dates, or combination.

how do address consolidation of sequential ID's originating on different client nodes (can be sidestepped in my context, but it would be interesting.)

dealing with collisions (is there a universally safe way to do so?).

general best practices.

how to structure the actual data transaction (ask for whole list then detect changes...)

答:
So I think in summary your questions relate to disconnected synchronization.

So here is what I think should happen:

Initial Sync
You retrieve the data and any information associated with it (row versions, file checksums etc). it is important you store this information and leave it pristine until the next succesful sync. Changes should be made on a COPY of this data.

Tracking Changes
If you are dealing with database rows, the idea is, you basically have to track insert, update and delete operations. If you are dealing with text files like xml, then its slightly more complicated. If it likely that multiple users will edit this file at the same time, then you would have to have a diff tool, so conflicts can be detected in a more granular level (instead of the whole file).

Checking for conflicts
Again if you are just dealing with database rows, conflicts are easy to detect. You can have another column that increments whenever the row is updated (i think mssql has this builtin not sure about mysql). So if the copy you have has a different number than what's on the server, then you have a conflict. For files or strings, a checksum will do the job. I suppose you could also use modified date but make sure that you have a very precise and accurate measurement to prevent misses. for example: lets say I retrieve a file and you save it as soon as I retrieved it. Lets say the time difference is a 1 millisecond. I then make changes to file then I try to save it. If the recorded last modified time is accurate only to 10 milliseconds, there is a good chance that the file I retrieved will have the same modified date as the one you saved so the program thinks theres no conflict and overwrites your changes. So I generally don't use this method just to be on the safe side. On the other hand the chances of a checksum/hash collision after a minor modification is close to none.

Resolving conflicts
Now this is the tricky part. If this is an automated process, then you would have to assess the situation and decide whether you want to overwrite the changes, lose your changes or retrieve the data from the server again and attempt to redo the changes. Luckily for you, it seems that there will be human interaction. But its still a lot of pain to code. If you are dealing with database rows, you can check each individual column and compare it against the data in the server and present it to the user. The idea is to present conflicts to the user in a very granular way so as to not overwhelm them. Most conflicts have very small differences in many different places so present it to the user one small difference at a time. So for text files, its almost the same but more a hundred times more complicated. So basically you would have to create or use a diff tool (Text comparison is a whole different subject and is too broad to mention here) that lets you know of the small changes in the file and where they are in a similar fashion as in a database: where text was inserted, deleted or edited. Then present that to the user in the same way. so basically for each small conflict, the user would have to choose whether to discard their changes, overwrite changes in the server or perform a manual edit before sending to the server.

So if you have done things right, the user should be given a list of conflicts if there are any. These conflicts should be granular enough for the user to decide quickly. So for example, the conflict is a spelling change from, it would be easier for the user to choose from word spellings in contrast to giving the user the whole paragraph and telling him that there was a change and that they have to decide what to do, the user would then have to hunt for this small misspelling.

Other considerations:
Data Validation - keep in mind that you have to perform validation after resolving conflicts since the data might have  changed
Text Comparison - like I said, this is a big subject. so google it!
Disconnected Synchronization - I think there are a few articles out there. too lazy to hunt for them now :c


答:
One reason is that, as a manager, you get an ok to recruit one "head". Not fractions. One.
This means, if you recruit someone part-time, you'll have to all effects one person in your team that does 3/5 of the work he/she's supposed to do or you will have to hire another person who wants to work the remaining 2/5.
However you see it, this turns quickly into an organizational problem in terms of coordination, effort, communication...
I think your best chance to work part time is to work as a consultant and do only the specific hours you need on the projects you're hired for. </p>


答:
I can think of a couple of reasons.

Companies that employ software developers recognise that they are developing a product to give them some sort of business advantage (eg: direct revenue, a process, etc...). Regardless of the specifics of the advantage, the company is going to want to jealously protect their intellectual property. Yes, company execs can be a very suspicious lot when it comes to this sort of thing, so in their minds they might be thinking, 'why does this person only want to work for me part of the time? Is this person working for someone else? Could this person become a risk to my IP?'

Companies are generally hiring people because they have determined a resourcing requirement that entails the need for a person to be working on a project for a certain amount of time in order to meet specific deadlines and targets.  The view therefore is that someone working part time will not allow them to fulfil the resourcing requirement in it's entirety, and;

a) The employer doesn't wish to face a need to employ additional staff,

b) There may be additional costs associated with hiring multiple part time staf in terms of benefits, payroll taxes, etc.

You are asking for a part time position when an advertised job may have specified full time.  Sometimes people think it strange that a candidate does not seem to have understood the requirements specified in a job description, and that this might suggest if such simple directions are not followed, perhaps the candidate won't pay attention to specifications.

You may have unwittingly presented the option in a way that makes it seem suspicious.

Perhaps the interviewer has already decided not to hire you, and unwittingly gives away a negative reaction to a question they feel is no longer relevant.

Just a few thoughts...  realistically speaking, most jobs in software development require full time staff.  You may later earn an option to shift to part time work, or you may find one of the rare roles out there that allow this, but it's likely to be hard.

As to specifically answering your first question, I'd answer that with, why would an employer give up the option for a programmer working entirely for his company's benefit full time for someone who the employer feels will only be putting in an effort for part of the time?


答:
Why, as an employer, would you give up a competent, even great, developer, simply because he wants to work 3 days a week and not 5?

More than one reason (all argued from the point of view of an employer):

As Fred Brooks argues in the book The Mythical Man-Month, the efficiency of a team goes down as the team size grows, because the amount of communication grows faster than linear with the team size. So N full-time developers are far more effective than 2N part-time developers, at the same cost.

If the developer is working on some important system, you want to be able to reach her at least during normal business hours.

A full time employee spends only eight hours at the office five days a week, but his mind is really working for the company 24 hours a day, seven days a week. That's why you sometimes wake up in the morning with the solution to a problem that's been bothering you for days - your mind doesn't stop working the moment you leave the office. For a part-time employee, I would fear the opposite: Instead of thinking about his day-job at home, I'd guess she'd think about her private problems at work.

How do I sell the story of part time job better?

Actually, I think the employers are mostly right, so I don't think you can "sell" it much better. But you could find a small company that doesn't have enough work for a full-time employee. They might be interested in hiring you part-time. Jobs like that probably wouldn't be very glamorous (or well-paid), though.

EDIT:
Your comments suggest that your don't have much working experience and that you can't imagine spending 40 hours per week at work. I can totally relate to that, sitting 40 hours a week in the cubicle next to Dilbert and Wally does sound like a horrible prospect.

If that's reasonably close, forget my advice about looking for a job at a company that doesn't have enough work for a full-time employee. These jobs certainly exists, but you won't learn much there (if they have only one part-time developer, who would teach you anything?), and they don't look very good on a resume (why did he start his career doing that? Couldn't he find a full-time job?). They'd probably be rather boring jobs, too, and IMHO spending 20 hours a week at a boring job is worse than spending 40 hours a week working on something you care about.

Instead try to find a full-time job where you get to build something interesting, where you like your co-workers and where you genuinely like going to work each morning. These jobs really are out there, and they're easier to find than part-time positions. There's still enough time to play StarCraft at the weekends ;-)


问:
Unit testing statically typed functional code
I wanted to ask you people, in which cases it makes sense to unit test statically typed functional code, as written in haskell, scala, ocaml, nemerle, f# or haXe (the last is what I am really interested in, but I wanted to tap into the knowledge of the bigger communities).

I ask this because from my understanding:

One aspect of unit tests is to have the specs in runnable form. However when employing a declarative style, that directly maps the formalized specs to language semantics, is it even actually possible to express the specs in runnable form in a separate way, that adds value?

The more obvious aspect of unit tests is to track down errors that cannot be revealed through static analysis. Given that type safe functional code is a good tool to code extremely close to what your static analyzer understands, it would seem that you can shift a lot of safety towards static analysis. However a simple mistake like using x instead of y (both being coordinates) in your code cannot be covered. OTOH such a mistake could also arise while writing the test code, so I am not sure whether it is worth the effort.

Unit tests do introduce redundancy, which means that when requirements change, the code implementing them and the tests covering this code must both be changed. This overhead of course is about constant, so one could argue, that it doesn't really matter. In fact, in languages like Ruby it really doesn't compared to the benefits, but given how statically typed functional programming covers a lot of the ground unit tests are intended for, it feels like it's a constant overhead one can simply reduce without penalty.

From this I'd deduce that unit tests are somewhat obsolete in this programming style. Of course such a claim can only lead to religious wars, so let me boil this down to a simple question:

When you use such a programming style, to which extents do you use unit tests and why (what quality is it you hope to gain for your code)? Or the other way round: do you have criteria by which you can qualify a unit of statically typed functional code as covered by the static analyzer and hence without need for unit test coverage?

答:
Yes, the unit tests already have sense with statically typed functional code. A simple example:

```<code>prop_encode a = (decode . encode $ a) == a
</code>```

You can force prop_encode with static type.

Body:
Yes, the unit tests already have sense with statically typed functional code. A simple example:

prop_encode a = (decode . encode $ a) == a

You can force prop_encode with static type.


答:
One aspect of unit tests is to have the specs in runnable form. However when employing a declarative style, that directly maps the formalized specs to language semantics, is it even actually possible to express the specs in runnable form in a separate way, that adds value?

It's very unlikely that you will be able to completely express your specifications as type constraints.

When you use such a programming style, to which extents do you use unit tests and why (what quality is it you hope to gain for your code)?

In fact, one major benefit of this style is that pure functions are easier to unit-test: no need to setup external state or check it after execution.

Often the specification (or part of it) of a function can be expressed as properties relating returned value to arguments. In this case using QuickCheck (for Haskell) or ScalaCheck (for Scala) can let you write down these properties as expressions of the language and check that they hold for random inputs.

Title: Unit testing statically typed functional code

Body:
I wanted to ask you people, in which cases it makes sense to unit test statically typed functional code, as written in haskell, scala, ocaml, nemerle, f# or haXe (the last is what I am really interested in, but I wanted to tap into the knowledge of the bigger communities).

I ask this because from my understanding:

One aspect of unit tests is to have the specs in runnable form. However when employing a declarative style, that directly maps the formalized specs to language semantics, is it even actually possible to express the specs in runnable form in a separate way, that adds value?

The more obvious aspect of unit tests is to track down errors that cannot be revealed through static analysis. Given that type safe functional code is a good tool to code extremely close to what your static analyzer understands, it would seem that you can shift a lot of safety towards static analysis. However a simple mistake like using x instead of y (both being coordinates) in your code cannot be covered. OTOH such a mistake could also arise while writing the test code, so I am not sure whether it is worth the effort.

Unit tests do introduce redundancy, which means that when requirements change, the code implementing them and the tests covering this code must both be changed. This overhead of course is about constant, so one could argue, that it doesn't really matter. In fact, in languages like Ruby it really doesn't compared to the benefits, but given how statically typed functional programming covers a lot of the ground unit tests are intended for, it feels like it's a constant overhead one can simply reduce without penalty.

From this I'd deduce that unit tests are somewhat obsolete in this programming style. Of course such a claim can only lead to religious wars, so let me boil this down to a simple question:

When you use such a programming style, to which extents do you use unit tests and why (what quality is it you hope to gain for your code)? Or the other way round: do you have criteria by which you can qualify a unit of statically typed functional code as covered by the static analyzer and hence without need for unit test coverage?


问:
Is COBOL still worth learning?
Does learning COBOL still make sense?</p>

答:
Nooo, of course not. COBOL is a dead language, after all. Or is it?

The problem with that view is that programmers at sites like this one usually work with high tech, fast-running (and equally fast burning-out) companies. For them COBOL is a dead language - it is nowhere to be seen. Has not been for some time now, 'tis true.

But COBOL was not meant for them. There is more to the software industry than this. Computers were not invented for people with some irrational need for upgrading and replacing old with new all the time. They were made for business purposes.

You want to see COBOL? Go to a company that processes payroll, or handles trucking of goods, or shipping (as in ships), or handles your bank account. There is a huge invisible system of code out there that's practically invisible to the users, and most of them never think about it although they encounter it in one way or another everyday (ATMs?)

No, it is not dead. But it is "legacy" for sure... or is it?

Again, depends how you look at it. Nowadays, a lot of people will use Java, C, or anything else instead of COBOL, rewriting from scratch... introducing new bugs as they go along, naturally. That is not saying COBOL doesn't have bugs, and quirks. It does, as much as the next language. Of course it does. But in "COBOL times", companies which took bugs more seriously than usual (insurance, banks) tended to produce higher quality code with special quality service groups; today, there are deadlines where time and budget always wins over quality. Also, these systems were originally developed for longer periods back then compared to the equivalent now.

If some software has been working for 30+ years, where is the incentive to switch? Whole companies went out of business because they ignored the old adage of "if it ain't broke, don't fix it." Many tried to rewrite the thing... then the first rewrite cost a lot, then the second one cost even more... and none of those new & improved managed to replace it. As I said, this industry is fast-burning, and it also tends to forget fast.

In the 70s COBOL was dead or dying soon, C/C++ were going to rule. Then again in the early 80s Pascal was taking over. Then in the 90s it was Java as THE Language...

Think of Unisys Mapper, dBase, Clipper, Cold fusion... do people even remember those? Each one of them was going to be the gravedigger for COBOL.

Taking that into account, and the fact that it is great for processing high volumes of transactions, batch processing or record/transaction-oriented processing, and that one can compile (without errors) a subroutine written 30 years old as managed COBOL code and call it from a managed COBOL.NET should one wish to go Windows and .NET, I'm having trouble finding a suitable replacement for it. (I'm also having trouble finding a Microsoft technology that lasted more then a decade.)

Yes, new COBOL code is being written today. One just has to know where to look.

For those laughing at COBOL, IMHO, it is like laughing at the Egyptian Pyramids, they are there from 5000 years and they still will be there in next 5000 years, while today's "hello world" housing needing 24 controls to work will be deleted, replaced, forgotten next month.

So where are all those COBOL programmers?

Ah, for here lies the rub. The thing is that a lot of them don't have any computing science background. A lot of them are not professional programmers (as in university graduates from a CS/SE program). For the most part, they are people in their late 30's-50's, from all areas of expertise, trained entirely by the company specifically for that job. So they aren't "COBOL programmers" - the training they got is specific to the company which so heavily promotes from within. And that makes them pretty much invisible.

Title: Is COBOL still worth learning?


答:
It depends,

binary operators in which order is important (asymmetric) benefit from infix notation as it is easier to distinguish which way round the operator will be evaluated e.g.

```<code>x.Operation(y); //so x is doing "Operation" to y
</code>```

compared to

```<code>Operation(x,y); //what was the order of arguments again?
</code>```

symmetric operators this is less of an issue, and indeed can sometimes by expanded to be n-ary operators with pre or post fix notation when associative e.g.

```<code>sum(1,2,3,4,5);
</code>```

for pre-fix vs post-fix I prefer prefix as like yoda, you talk, with post-fix

last of all here is what dijstra had to say on the subject in essence he favoured infix for associative operations

Title: Infix vs Prefix Notation - Which do you prefer?

Body:
I have been learning Clojure and looking at Scheme and CL which introduced me to the world of prefix notation. At first I didn't like it but it is still starting to grow on me. To be honest though, there are still long calculations that are difficult for me to understand but I think that is an issue of me needing more exposure/practice and I'll get it.

But that leads me to the question: Which type of notation do you prefer and why?

Body:
It depends,

binary operators in which order is important (asymmetric) benefit from infix notation as it is easier to distinguish which way round the operator will be evaluated e.g.

x.Operation(y); //so x is doing "Operation" to y

compared to

Operation(x,y); //what was the order of arguments again?

symmetric operators this is less of an issue, and indeed can sometimes by expanded to be n-ary operators with pre or post fix notation when associative e.g.

sum(1,2,3,4,5);

for pre-fix vs post-fix I prefer prefix as like yoda, you talk, with post-fix

last of all here is what dijstra had to say on the subject in essence he favoured infix for associative operations


问:
Python for large projects
Are there any resources out there on how to architect large, industrial strength Python projects? I'd like to start on an ambitious personal project, but I'm not really sure how to architect it and what practices to put into place to make the project successful. </p>

<p>Are there any resources out there discussing how to make large Python projects work? </p>

答:
I don't think there's anything specific to large Python projects that wouldn't apply to large projects in other programming languages as well.

In any large project, you ought to aim for loose coupling and high cohesion. A large project is manageable if it is made up of orthogonal, as-self-contained-as-possible subprojects. Tests are useful for the process of creating the subcomponents one by one, as well as keeping them working while modifying them later on as you better find out what they should be, as the whole starts to take shape.

OwnerDisplayName: Alex

Title: Python for large projects


问:
Use open-source programs in your company?
Is there any cons of making your employees use open-source programs in your company?

I am planning to start a bussiness and I wonder why companies usually work with proprietary software, as Microsoft Word to quote the most famous one. Why do not they use Open Office (or Libre Office) etc.?

From my point of view, you can save a lot of money and help the open-source community by, for instance, giving them part of your benefits in form of donations.

I do not know any (medium-big) company that does this. Probably you could give me some examples, just to prove that this model of open-source usage/collaboration works rocks.

答:
As a startup, you are free to choose whichever platform best suits your needs. Big-medium organisations are established companies that have been around for a long time. They will have chosen what was best for them when they began, but since then will probably have had to stick with that choice, either due to contractual agreements or due to the cost of converting (in terms of re-training staff and converting existing documents over to the new format).

Also, the cost of proprietary software is often not as bad as you might think. For example, Microsoft Action Pack is about $329 a year, and offers 10 copies of Windows 7, 10 copies of Office, as well as many copies of other software products such as Windows Server, SQL Server, Sharepoint etc.

For new start-ups, they also offer various packages, some of which are free. I know there is a package that allows new startups to get Visual Studio free for 3 years.


问:
Getting from a user-story to code while using TDD (scrum)
I'm getting into scrum and TDD and I think I have some confusion which I'd like to get your feedback about. Let's assume I have a user-story in my backlog, in order for me to start developing it as part of TDD I need to have requirements, right so far?

Is it true to say that the product manager and the QA should be responsible for taking the user-story and breaking it down to acceptance tests?

I think the above is true since the acceptance tests need to be formal, so they can be used as tests, but also human readable so that the product can approve they are the requirements, right?

Is it also true that I later take these acceptance tests and use them as my requirements, i.e. they are a set of use-cases which I implement (through TDD)? I hope I'm not making too much of a mess but that's the current flow I have in mind right now.

Update

I think my initial intentions were unclear so I'll try to rephrase. I want to know more details about the scrum flow of turning a user-story into code while using TDD.

The starting point is obvious, a user surfaces a need (or the user's representative as the product) which is a short 1-2 lines description in the known format and that is added to the product backlog.

When there is a spring planning meeting user-stories are taken from the backlog and assigned to developers.

In order for a developer to write code they need requirements (especially in TDD since the requirements are what the tests are derived from).

When, by whom and to which format are the requirements compiled?

What I had in mind was that the product and QA define the requirements via acceptance tests (I'm thinking of automatic using FitNesse or the sort but that's not the core I think) which help to serve 2 purposes at the same time:

They define "Done" properly.

They give a developer something to derive tests from.

I wasn't sure when these were written (before the sprint they're picked then that might be a waste since additional information will arrive or the story won't be picked, during the iteration then the developer might get stuck waiting for them...)

答:
User story is not "As a user I want XXX so that YYY"! User story is promise for future communication with PO. That solves your problem with more details. You must communicate with PO during sprint to get any information you need.

User story also has more features then the short sentence promising the communication. Necessary part of user story are acceptance criteria. Acceptance criteria must be known prior to committing to user story (they should be known prior to estimating user story). Acceptance criteria are the input for acceptance tests = acceptance tests should test acceptance criteria.

So when you start work on user story with TDD approach you (not QA) should first create automated acceptance test based on acceptance criteria to get failing test for it. You will continue with implementing necessary code using TDD before the acceptance test pass. You will continue with next acceptance test. I wrote about that also in another question.


答:
Most of the bases have been covered.  You could try looking for a company that allows more flexible working.  For example, my company allows 2 people to share a job.  You agree with a colleague doing the same job which days you work and get paid on a pro rata basis.  I have considered taking advantage of another scheme that basically allows me to work only during school hours on school days to allow me to care for my daughter.
That said, however, they are only open, so far as I know, to established employees.  </p>


答:
One aspect of unit tests is to have the specs in runnable form.
  However when employing a declarative style, that directly maps the
  formalized specs to language semantics, is it even actually possible
  to express the specs in runnable form in a separate way, that adds
  value?

If you have specs which can be mapped directly to function declarations - fine. But typically those are two completely different levels of abstractions. Unit tests are intended to test single pieces of code, written as white box tests by the same developer who is working on the function. Specs normally look like "when I enter this value here and press on this button, this and that should happen". Typically such a spec leads to far more than one function to be developed and tested.

However a simple mistake like using x
  instead of y (both being coordinates) in your code cannot be covered.
  However such a mistake could also arise while writing the test code,
  so I am not sure whether it is worth the effort.

Your misconception is here that unit tests are actually for finding bugs in your code first hand - that's not true, at least, it is only partially true. They are made to prevent you from introducing bugs later when your code evolves. So when you first had your function tested and your unit test working (with "x" and "y" properly in place), and then while refactoring you use x instead of y, then the unit test will show that up to you.

Unit tests do introduce redundancy, which means that when requirements
  change, the code implementing them and the tests covering this code
  must both be changed. This overhead of course is about constant, so
  one could argue, that it doesn't really matter. In fact, in languages
  like Ruby it really doesn't compared to the benefits, but given how
  statically typed functional programming covers a lot of the ground
  unit tests are intended for, it feels like it's a constant overhead
  one can simply reduce without penalty.

In engineering, most safety systems rely on redundancy. For example, two breaks in a car, a redundant parachute for a sky diver etc. The same idea applies to unit tests. Of course, having more code to change when the requirements change can be a disadvantage. So especially in unit tests it is important to keep them DRY (follow the "Dont Repeat Yourself" principle). In a statically typed language, you may have to write some less unit tests than in a weakly typed language. Especially "formal" tests may be not necessary - which is a good thing, since it gives you more time to work on the important unit tests which test substantial things.  And don't think just because you static types, you don't need unit tests, there is still plenty of room to introduce bugs while refactoring.


答: A development team can be considered a fully connected network, which means there are n(n - 1) / 2 "interfaces" between the developers. In practice this means that going from five to seven developers, the team suddenly has more than twice the opportunity for friction, communications failures and misunderstandings.</p>


答:
The explanations are important.

I would hope that a modern employer would recognise work-life balance as a reasonable goal. Especially if you have a family or some similar responsibility.

I would not say that you want to work on your own projects, which will make the employer suspect that you might goof off and work on them when you should be working for the employer, or that you might quit soon to work on them full time.

You could say that you already have a part-time commitment and you need some more part-time work to build up your income. Make the part-time commitment sound commercial. For example "I need to do a little support for some existing clients" is good, it gives an impression that you have some business sense. "I want to work on my own projects" is less good, it gives the impression that you might goof off to work on a pet open-source project.


问:
Is it okay to have many Abstract classes in your application?
We initially wanted to implement a Strategy pattern with varying implementations of the methods in a commmon interface. These will get picked up at runtime based on user inputs.

As it's turned out, we're having Abstract classes implementing 3 - 5 common methods and only one method left for a varying implementation i.e. the Strategy.

Update: By many abstract classes I mean there are 6 different high level functionalities i.e. 6 packages , and each has it's Interface + AbstractImpl + (series of Actual Impl).

Is this a bad design in any way?

Any negative views in terms of later extensibility - I'm preparing for a code/design review with seniors.

答:
Template Method Patterns make subclass to implement special code by abstract method and the subclass inherits common method from superclass.
So i do not think this has many Abstract classes, it is only one Abstract classes, all subclass is instance class.</p>


答:
A thought that strikes me as I read the other well thought out answers is that if you want part time work, why aren't you considering short term contract positions?  In this area, that is the norm for developers who want free time to work on their own projects.

This way you can usually work off site and manage your own time, be confident in your earnings and still know that you'll have time to work on your projects.  Work 3 months full time, take the next 2 off.  During that 2 you line up your next contracts.


答:
Python is definitely good for large projects. This, IMO, is one of the reasons Python is so popular. Actually, there are several large projects that use Python such as Chandler - A note to self system. There is also this link I found on SO.

As far as how YOU can do it, get somebody'(s) help, and start off with a small project on your own computer. Migrate that to SourceForge and get more developers. If you stick with this project you can make a big Python project. You really don't need a resource for this. Just start coding. And if you need any help, feel free to email me:-).

Hope this helps!

Title: Python for large projects

Body:
Are there any resources out there on how to architect large, industrial strength Python projects? I'd like to start on an ambitious personal project, but I'm not really sure how to architect it and what practices to put into place to make the project successful. </p>

<p>Are there any resources out there discussing how to make large Python projects work? </p>


答:
In the year 2000 I read a statistic that there were more lines of COBOL written than all other languages combined.
Add to that the IBM guarantee that any TEXT deck (object code), compiled on any MVS system is executable on all of their MVS systems and you have a guarantee that there will be COBOL programming around as long as the sun shines.

Title: Is COBOL still worth learning?

Body: Does learning COBOL still make sense?</p>


问:
Discovering elegant ways of coding
I read this thread on programmers today and thought that looked like a really elegant way of coding. I would like to discover more neat methods of coding.

What are the best ways of discovering new elegant ways of coding? (Im already aware of the standard design patterns)

答:
I do always equate elegant code with readable code and code which is really easy to understand.

In my opinion you don't have to follow many patterns and practices.

Just lean back and think :

would a coworker or reviewer understand this immediately ?

Title: Discovering elegant ways of coding