问:
I've inherited 200K lines of spaghetti code -- what now?
I hope this isn't too general of a question; I could really use some seasoned advice.

I am newly employed as the sole "SW Engineer" in a fairly small shop of scientists who have spent the last 10-20 years cobbling together a vast code base. (It was written in a virtually obsolete language: G2 -- think Pascal with graphics). The program itself is a physical model of a complex chemical processing plant; the team that wrote it have incredibly deep domain knowledge but little or no formal training in programming fundamentals. They've recently learned some hard lessons about the consequences of non-existant configuration management. Their maintenance efforts are also greatly hampered by the vast accumulation of undocumented "sludge" in the code itself. I will spare you the "politics" of the situation (there's always politics!), but suffice to say, there is not a consensus of opinion about what is needed for the path ahead.

They have asked me to begin presenting to the team some of the principles of modern software development. They want me to introduce some of the industry-standard practices and strategies regarding coding conventions, lifecycle management, high-level design patterns, and source control. Frankly, it's a fairly daunting task and I'm not sure where to begin.

Initially, I'm inclined to tutor them in some of the central concepts of The Pragmatic Programmer, or Fowler's Refactoring ("Code Smells", etc). I also hope to introduce a number of Agile methodologies. But ultimately, to be effective, I think I'm going to need to hone in on 5-7 core fundamentals; in other words, what are the most important principles or practices that they can realistically start implementing that will give them the most "bang for the buck".

So that's my question: What would you include in your list of the most effective strategies to help straighten out the spaghetti (and prevent it in the future)?

答:
Do the analysis first.

I would do some analysis before deciding what to teach.  Figure out where the biggest pain points are.  Use those to prioritize what practices to go over.

Introduce only a few changes at a time (in a similar situation I did 2-3 practices every 2 weeks).

I would limit the practices to ~3 depending on level of change to there programming style of SDLC; until they start to get comfortable with them (I would push to introduce 1 new change every ~1-2 weeks as they get more comfortable with the idea of learning new approaches).  It's also a good idea to identify what the criteria for success is.  What the practice should accomplish (even if it's a soft goal like team morale).  That way you can show if it's effective or not.

Why limit the number of changes?

Even if you assume these people want to be better programmers and are open to learning there are limits to how much and how fast people can learn new concepts and apply them; especially if they don't have CS foundation or have participated in a Software Development Life Cycle previously.

Add a weekly wrap-up meeting to discuss how the practices affected them.

The meeting should be used to discuss what went well and what needs work.  Allow them to have a voice and be collaborative.  Discuss and make plans to address problems they are having and to preview the next changes coming up.  Keep the meeting focused on the practices and their application.  Do a little evangelizing on the benefits they should start to see from applying the practices.

Certain practices take precedence.

Proper use of a version control system (IMO) trumps everything else.  Close behind are lessons in modularization, coupling/cohesion and feature/bug ticket tracking.

Remove practices that don't work.

Don't be afraid to get rid of practices that don't work.  If there is a high cost and little to no benefit, remove the practice.

Improvement is a process.

Convey that sustained, consistent improvement is a process.  Identify the biggest pain points, apply a solution, wait/coach and then repeat.  It will feel agonizingly slow initially until you build up some momentum.  Keep everyone focused on the improvements that are coming and the improvement that are already successful.


问:
Java: "Heap pollution"
A "Heap Pollution" as in Non-Reifiable Types (The Java™ Tutorials > Learning the Java Language > Generics (Updated))

Why is it called that way?

答:
Heap pollution simply implies that you have "bad stuff" in your heap.  It is an analogy to (for example) water pollution which is where you have "bad stuff" in the water.

Specifically, the bad stuff here is objects of type A where you ought to have objects of type B ... according to the static typing.  Some hole in the static typing is allowing the bad stuff to leak into the heap ... where it is liable to cause damage (e.g. unexpected ClassCastExceptions) at runtime.

It is not a particularly good analogy, but it is the terminology that the Java folks coined ... and they have (in effect) defined it in the page that you linked to, and probably other places.

But still - there should be a reason / mnemonic device behind that name.

Why should there be?  There are lots of words and phrases in use in English where nobody really knows the origin or the reasoning.  Or where the origin is known, but is illogical.  For example, the supposed origin of the term "bug" referring to a flaw in a computer program.  Or the current meaning of the term "quantum leap" in popular culture.  Or the word "gay".

(But, in the case of "heap pollution", the source >>is<< known, and the reasoning behind the choice of the term >>is<< self evident ... to people from the same linguistic and cultural background as the authors.)

It is funny but even google does not seem to know why.

Not really.  It just means that nobody had previously thought to ask for a definition in a place that Google indexes.  The usage is restricted to the Java programming (as far as I am aware), and the analogy is obvious ... to most people who would use the term.

8 years later, this is still the only page that tries to answer the "why" question.  I guess, "self evident" covers it adequately :-)

ContentLicense: CC BY-SA 3.0

Title: Java: "Heap pollution"

ContentLicense: CC BY-SA 4.0


问:
Is Entity Framework ready for production?
I'm looking into Entity Framework for a new project that I'm going to be taking on and as part of my research into it I'm asking some industry professionals if it's stable and ready for 'real world' implementation.

In the running is:

EF

NHibernate

DevExpress XPO

I already have a great deal of experience with XPO, but I'm not particularly happy with it.

答:
I think/hope so... I'm starting a project with EF 4 and the new Model-First approach...

For what I've seen EF 4 is much robust and feature complete that the first version... I would say go for it, I know I'm going :)

ContentLicense: CC BY-SA 2.5


问:
Performance of concurrent software on multicore processors
Recently I have often read that, since the trend is to build processors with multiple cores, it will be increasingly important to have programming languages
that support concurrent and parallel programming in order to better exploit the parallelism offered by these processors (see e.g. this video for some background.).

In this respect, certain programming paradigms or models are considered well-suited for writing robust concurrent software:

Functional programming languages, e.g. Haskell, Scala, etc.

The actor model: Erlang, but also available for Scala / Java (Akka), C++ (Theron, Casablanca, ...), and other programming languages.

My questions:

What is the state of the art regarding the development of concurrent applications (e.g. using multi-threading) using the above languages / models? Is this area still being explored or are there well-established practices already?

Will it be more complex to program applications with a higher level of concurrency, or is it just a matter of learning new paradigms and practices?

How does the performance of highly concurrent software compare to the performance of more traditional software when executed on multiple core processors?

For example, has anyone implemented a desktop application using C++ / Theron, or Java / Akka? Was there a boost in performance on a multiple core processor due to higher parallelism?

EDIT

NOTE that I am not asking for your opinions or for debate but for concrete experiences or information. For example, has anyone written a Scala or Haskell program, compiled it with existing state-of-the-art compilers, and

Run it on an Intel Core i3 and measured a certain performance (e.g. 10 seconds on certain input data).

Run the same bytecode or binary on an Intel Core i5 and observed a performance boost (e.g. 6 seconds running time) due to the parallel computation of sub-expressions which is possible in functional code?

EDIT 2

SUMMARIZING.
Up to now making faster processors meant increasing the clock speed, and no changes in programming paradigm were needed. In the last few years making faster processor has meant adding more cores but this requires we write software differently. My question is whether software developers are starting to switch to new programming paradigms and whether this is bringing the expected performance boost on multiple-core processors.

答:
You cannot magically make code not written for concurrency work well concurrently (and magically includes using compilers).

Many times conditions have changed and code needed to be done differently.  In the very old days, memory was a premium, so self-modifying code was common.  These days, the benefits of code in memory being read-only are so great that all modern operating systems want to enforce it.

Also think what happened when Windows became popular.  All the DOS programmers had to rethink their programming ways.  You could not have a single keyboard polling loop invoking the complete application functionality in a single threaded program - you had to have event handlers - which in turn changed the way the application code was designed.

Mantras like "use immutable objects!" are experiences learned the hard way.  The reasons why are frequently lost on the way but can be reconstructed.  The "use immutable objects" is a simple way to allow caching data multiple places without having your program break by one of these places being updated.

The change needed to be concurrent does not need to be a full rewrite in a functional language, but can be solved with libraries - which allows to keep existing code libraries - but  you still need to write your program to utilize it.  The OpenCL (Grand Central in OS X) approach is a very interesting way to use both CPU and GPU's to execute code, but again you need to make your program accordingly.

In Java a lot of effort has been spent on providing good building blocks for transparently scale the executing of small code snippets, but you cannot use it if you do not write for it.


问:
how can python interpreter recognize code block
The most unusual aspect of Python is that whitespace is significant

instead of block delimiters (braces → "{}" in the C family of languages), indentation is used to indicate where blocks begin and end.

how can python interpreter recognize code block ?

答:
A block begins when the indentation increases.

A block ends when the indentation decreases.

Multiple blocks can be closed in the same decrease.

Blocks can nest.

Sequential blocks at the same indentation depth join up.


答:
Remember that whitespace appears as just another character to the interpreter.

A tab is 0x09 in ASCII

A space is 0x20 in ASCII

An interpreter is little more than a pattern matcher that then triggers predefined rules.

Body:
The most unusual aspect of Python is that whitespace is significant

instead of block delimiters (braces → "{}" in the C family of languages), indentation is used to indicate where blocks begin and end.

how can python interpreter recognize code block ?


问:
Object Oriented programming and modelling
I am taking a course in OOA/D this semester. I have some doubts about Object Oriented Programming.

Is it true that Object Oriented programming can be done without any specific modelling like OMT?

What are the models available for object Oriented software development?

答:
OO development was being done long before modeling tools existed.  The modeling tools were created as a way to assist OO development.  Whether or not they have really succeeded in making OO development easier is the subject of a different question.

For that matter, you can perform OO like development in non-OO languages.  It's difficult to simulate inheritance and polymorphism without language support, but the aspects of encapsulation and information hiding don't require specific OO language constructs.


答:
At the parser level, it's not all that difficult. The parser just needs a variable to keep track of the indentation level of the current block.  And when it goes to read a new line, it counts leading spaces (or tabs) and compares the value against the indentation of the current block, then apply an algorithm that looks something like this:</p>

```<code>if currentIndent = currentBlock.indent then
   parse line in the context of currentBlock
else if currentIndent > currentBlock.indent then
   create sub-block of currentBlock and parse line in that context
else finish currentBlock and run this same comparison on currentBlock.parent
</code>```

Title: how can python interpreter recognize code block

Body:
At the parser level, it's not all that difficult. The parser just needs a variable to keep track of the indentation level of the current block.  And when it goes to read a new line, it counts leading spaces (or tabs) and compares the value against the indentation of the current block, then apply an algorithm that looks something like this:

if currentIndent = currentBlock.indent then
   parse line in the context of currentBlock
else if currentIndent > currentBlock.indent then
   create sub-block of currentBlock and parse line in that context
else finish currentBlock and run this same comparison on currentBlock.parent


问:
moving from Windows to Linux
I need to reconcile these 2 facts:

I don't feel comfortable working on Linux;

I need to develop software for Linux.

Some background: I have a 10+ years of programming experience on Windows (almost exclusively C/C++, but some .NET as well), I was a user of FreeBSD at home for about 3 years or so (then had to go back to Windows), and I've never had much luck with Linux. And now I have to develop software for Linux. I need a plan.

On Windows, you can get away with just knowing a programming language, an API you're coding against, your IDE (VisualStudio) and some very basic tools for troubleshooting (Depends, ProcessExplorer, DebugView, WinDbg). Everything else comes naturally.

On Linux, it's a very different story. How the hell would I know what DLL (sorry, Shared Object) would load, if I link to it from Firefox plugin? What's the Linux equivalent of inserting __asm int 3/DebugBreak() in the source and running the program, and then letting the OS call a debugger? Why the hell release builds use something, called appLoader, while debug builds work somehow different? Worst of all: how to provision Linux development environment?

So, taking into account that hatred is usually associated with not knowing enough, what would you recommend? I'm ok with Emacs and GCC. I need to educate myself as a Linux admin/user, and I need to learn proper troubleshooting tools (strace is cool, btw), equivalents to the ones I mentioned above.

Do I need to do Linux from Scratch? Or do I need to just read some books (I've read "UNIX programming environment" by Kernighan and "Advanced Programming..." by Stevens, but I need to learn something more practical)? Or do I need to have some Linux distro on my home computer?

答:
Consider this: you once didn't know anything about Windows, but you learned it and over time became comfortable with it.

Then MS changed whatever programming system you were comfortable with to .NET and you no longer knew anything about DLLS, COM, and whatever, you had to learn things like assemblies, GAC, app domains. You learned those ok.

So why are you now worried about doing the same with Linux?

There are loads of 'get you started' tutorials on the web for all kinds of programming environments. Now you say GCC so I'm going to assume C++ development. Get yourself Eclipse, install the CDT (c dev tools) on top of your Eclipse platform (Eclipse is a multi-purpose IDE, you can use it for C++, PHP, Java, whatever - but you need to install the tooling for your language as you wouldn't really want it all pre-installed like VS and take 3 days to install :) )

There are easy-to-use tutorials all over the web. IBM has one here that is quite comprehensive.

Debugging tools... eclipse has it embedded (tutorial), but you can find plenty of tools like the ones you mentioned, just search around the web and you'll find lots of options. It will take you a little while to figure out how to read a core dump (as opposed to a windows userdump for example) but you'll get there.

It might also be worthwhile starting a blog with your experiences, not only will it allow you to remind yourself of what you've done (eg setting up eclipse how you like it, you'll forget when you need to do it again in a year's time) but it'll help others in your situation.

OwnerDisplayName: rincewind

Title: moving from Windows to Linux


问:
IPC linux huge transaction
I'm building and application that requires huge transactions/sec of data and I need to use IPC to for the mutithreaded mutliprocceses communication, I know that there are a lot of methods to be used but not sure which one to choose for this application. </p>

<p>This is what the application is gonna have,
4 processes, each process has 4 threads, the data chunk that needs to be transferred between two or more threads is around 400KB. I found that fifo is good choice except that it's 64K which is not that big so i'll need to modify and recompile the kernel but not sure if this is the right thing to do?
Anyway, I'm open to any suggestions and I'd like to squeeze your experience in this :) and I appreciate it in advance.  </p>

答:
I maninly program for Windows but I think that the solutions are the same for Linux. I would use one of the following:

Named Pipes: Fast, have build in client server paradigm, work nice with multiple threads, eg. multiple readers / single writter etc...

Shared memory: Probably the fastest method of IPC, but you need to do your own synchronization, resource locking etc...

Sockets: Same as Pipes, little bit slower, but can communicate over machines or internet.

I would go for Named Pipes. I use them a lot and they are fast and reliable. Also if you need to move so much data per second (don't know exactly how much) them maybe you need to rethink your approach. Extremes often show bad design choices.

EDIT:

For names pipes here is a basic example.

Title: IPC linux huge transaction


问:
What's the difference between using RDFS/OWL versus XML?
I was wondering what advantages the ontology languages of RDFS/OWL has over using a tagging/markup system (such as http://www.schema.org/) for managing and creating metadata?</p>

答:
RDF/OWL vs XML is false alternative. In fact one of popular serialization is using XML.

Also RDF/OWL vs microformats is false alternative. In fact there are standards that allow using RDF as an microformat, eRDF and W3C's official RDFa with standardized way of embedding it in HTML5.

So truly the question is what the advantage of using standard, W3C approved formats. Reasons are:

there are multiple ontologies already out there including most widely used ones as Dublin Core and FOAF.

multiple triple-stores compatible with RDF/OWL for most any programming language.

various of above mentioned triple-stores feature inference engines with SPARQL interface.

Overall, I don't see any reason why should you go for non-standard, non-W3C microformat.


答:
Is it true that Object Orinted programming can be done without any specific modelling like OMT.

OOP is a way to program - Modeling is a way to facilitate thinking and documentation of specifications and requirements of a system. Object Modeling is a modeling type that focuses on modeling techniques using Objects.

What are the models available for object Oriented software development?

OOP is often modeled via Unified Modeling Language (UML). However, UML is a specification not a methodology, it does not tell you what to do. UML is not required to create working OO programs.

OOP practitioners and theorists have collected and presented some useful experiences for common programming situations in what is referred to as patterns (see for example: Wiki-Design Patterns.

Title: Object Oriented programming and modelling

Body:
I am taking a course in OOA/D this semester. I have some doubts about Object Oriented Programming.

Is it true that Object Oriented programming can be done without any specific modelling like OMT?

What are the models available for object Oriented software development?


问:
Where is the application of Calculus (of continuous quantities) in Computer Science or programming
I am a Software Engineer professional. I have studied calculus as a core course in my graduation studies. I want to ask question, that what/where is the implementation of calculus in computer science?</p>

答:
I work in the Aerospace industry on spacecraft (mostly satellites) modeling and simulation software.  Most recently, I was was responsible for developing a simulation model for a satellite's attitude determination and control system.

Yes, I had to use a lot of math, mostly linear algebra and calculus.  While many of the physics calculations my software had to perform were well known, and the scientists and systems folks basically handed me documentation (or sometimes, their matlab scripts) for most of them, being able to convert math formulas into code is easier if you understand what the formulas are doing :)

Also, tracking down bugs and finding the occasional error in the equations I was handed would have been nigh on impossible if I had absolutely no math background.


答: The Python documentation, in the Lexical Analysis section, describes briefly how the indentation parsing works. In short, the tokeniser generates special INDENT and DEDENT tokens that are used by the parser when deciding where blocks of code start and end. These tokens (roughly) correspond to the { and } tokens in C-like languages.


问:
Oracle has some very helpful and free code...I think
I found that some of the code that Oracle uses is very useful so I don't have to re-invent the wheel.

Given this is at the top of the file where the code in question is:

```<code>/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.  Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
</code>```

If I leave the text intact, put it in my C++ header, and credit oracle for each method, and package the source into a static library...is it still a no-no?

答: After reading the links provided by cpeisert in the comments I have decided that the GPL is too restrictive (weird, right?) for the distribution plan I have for this library. As such, I have removed the GPL'd code and rolled my own solutions.</p>


问:
How do I reuse a state machine in a slightly different way?

Problem

I have a big state machine. The design requirements of the project have changed such that I need to re-use this state machine in another place. All the states remain the same in this new place, but a few states run slightly different stuff. What design pattern allows me to reuse this state machine?

Motivation

I am building a video player. It is modeled by a state machine with these states: stopped, loading, playing, paused, crashed, and some more... This video player needs to be used on two web pages. When the player crashes on the first page, it should show an error message below. If the player crashes on the second page, the error message should appear in the center of the video and pulsate a few times.

答:
personally, I would have state changes call a method based on an interface - that way you can plug any compatible model into it

as for your specific example, you could subclass the video-player code and override the 'Crashed' state method to provide different behaviors


问:
Programming SOLID Principles
Over time I could understand two parts of SOLID – the “S” and “O”.

“O” – I learned Open Closed Principle with the help of Inheritance and Strategy Pattern.

“S” – I learned Single Responsibility principle while learning ORM (the persistence logic is taken away from domain objects).

In a similar way, what are the best regions/tasks to learn other parts of SOLID (the “L”, “I” and “D”)?

References

msdn - Dangers of Violating SOLID Principles in C#

channel9 - Applying S.O.L.I.D. Principles in .NET/C#

OOPS Principles (SOLID Principles)

答:
Liskov Substitution Principle basically does not let you to overuse implementation inheritance: you should never use inheritance just for code reuse (there is composition for this)! By adhering to LSP, you can be pretty sure that there actually exists a "is-a relationship" between your superclass and your subclass.

What it says is that your subclasses must implement all of the methods of the subclass in a similar way to the implementation of the methods in the subclass. You should never override a method with implementing NOP or return null when the supertype throws exception; stated in Design by Contract terms, you should respect the contract of the method from the superclass when overriding a method. A way to defend against breaking this principle is by never overriding an implemented method; instead extract an interface and implement that interface in both classes.

Interface Segregation Principle, Single Responsibility Principle and High Coehsion Principle from GRASP are somehow related; they refer to the fact that an entity should be responsible for only one thing so that there is only one reason for change so that change is done very easily.

It actually says that if a class implements an interface then it must implement and use all those interface's methods. If there are methods that ar not needed in that particular class, then the interface is not good and must be splitted into two interfaces one that has only the methods needed by the original class. It can be regarded from a POV, that relates to the previous principle by the fact that it does not let you create large interfaces so that their implementation could break LSP.

You can see Dependency Inversion in the Factory Pattern; here both the high-level component (the client) and the low-level component (individual instance to be created) depend upon the abstraction (the interface).
A way to apply it in a layered architecture: you should not define an interface to a layer in the layer that is implemented but in the module that is called. For example the API to the data source layer should not be written in the data source layer but in the buisness logic layer, where it is needed to be called. In this way, the data source layer inherits/depends on the behavior defined in the buisness logic (thus the inversion) and not vice-versa (as would be in a normal way). This provides flexibility in the design, letting the business logic work without any code change, with another entirely different data source.

Title: Programming SOLID Principles


问:
How can I check myself when I'm the only one working on a project?
I'm in between jobs in my field (unrelated to software development), and I recently picked up a temporary side contract writing a few applications for a firm. I'm the only person working on these specific applications. Are there ways I should be checking myself to make sure my applications are sound? I test my code, try to think of edge cases, generate sample data, use source control, etc. but since I'm the only person working on these applications, I'm worried I'll miss bugs that would easily be found in a team environment. Once I finish the application, either when I'm happy with it or when my deadline expires, the firm plans to use it in production. Any advice? Not to use a cliche, but as of now, I simply work "to the best of my ability" and hope that it's enough.

Incidentally, I'm under both strict NDA's and laws about classified material, so I don't discuss the applications with friends who have actually worked in software development. (In case it's not obvious, I am not a software developer by trade, and even my experience with other aspects of information technology/computer science are limited and restrained to dabbling for the most part).

答:
I would suggest that you plan UAT (User acceptance test) sessions with your client.

Usually, it is done at every iteration, or when you have some block of functionality ready for review. This will give you nice feedback before rolling to production.


答:
If you're passing large amounts of memory around, you absolutely need shared memory. The moment you copy that 400k buffer you're taking a large perf hit.

So if you allocate the buffers in a shared memory area, you can just pass the reference/pointer/handle/whatever around and you're good. You will have to be careful about simultaneous writing to these buffers, but that's still much faster than passing a copy around. Its quite easy to do as well if you keep a 'in use' block at the beginning of the buffer too.

On Linux, shmget is the place to start.

Title: IPC linux huge transaction

Body:
I'm building and application that requires huge transactions/sec of data and I need to use IPC to for the mutithreaded mutliprocceses communication, I know that there are a lot of methods to be used but not sure which one to choose for this application. </p>

<p>This is what the application is gonna have,
4 processes, each process has 4 threads, the data chunk that needs to be transferred between two or more threads is around 400KB. I found that fifo is good choice except that it's 64K which is not that big so i'll need to modify and recompile the kernel but not sure if this is the right thing to do?
Anyway, I'm open to any suggestions and I'd like to squeeze your experience in this :) and I appreciate it in advance.  </p>


问:
Constructs for wrapping a hardware state machine
I am using a piece of hardware with a well defined C API. The hardware is stateful, with the relevant API calls needing to be in the correct order for the hardware to work properly. The API calls themselves will always return, passing back a flag that advises whether the call was successful, or if not, why not. The hardware will not be left in some ill defined state. In effect, the API calls advise indirectly of the current state of the hardware if the state is not correct to perform a given operation. It seems to be a pretty common hardware API style.

My question is this: Is there a well established design pattern for wrapping such a hardware state machine in a high level language, such that consistency is maintained?

My development is in Python. I ideally wish the hardware state machine to be abstracted to a much simpler state machine and wrapped in an object that represents the hardware. I'm not sure what should happen if an attempt is made to create multiple objects representing the same piece of hardware.

I apologies for the slight vagueness, I'm not very knowledgeable in this area and so am fishing for assistance of the description as well!

答:
What's wrong with just keeping track of the state in an int? Then on each API call you check if the operation is allowed in the current state, although this can get tedious if there are tens or more states.

If you really feel the need to go all design patterny then maybe the State Pattern would interest you.


问:
Should a standard include header be specified in each file or as a compiler parameter?
I've got a file such as this:

```<code>#ifndef STDINCLUDE
#define STDINCLUDE

#include <memory>
#include <stdexcept>

#endif
</code>```

I want this file to be included in every header file, because I use stuff from those headers so much. Is it preferable to include this via compiler options (-I stdinclude.hpp), or should I physically include them in each header? (#include <stdinclude>). Note that I am attempting to be cross-platform-minded. I use cmake to serve atleast Unix and Windows.

答:
It's a good idea to #include whatever files a source file relies on. If you have a standard set of headers to be included in every file, #include them all in a single header file like your stdinclude.hpp. That way, you only have to edit one file when you change the set of standard headers.

That said, you don't want to have to compile each of those header files in the standard set every time you compile one of your source files. Most compilers provide a mechanism for creating a precompiled header for just this reason. A precompiled header lets you avoid having to compile the same header files over and over, significantly reducing the build time for your project.


问:
How to do MVC the right way
I've been doing MVC for a few months now using the CodeIgniter framework in PHP but I still don't know if I'm really doing things right.

What I currently do is:

Model - this is where I put database queries (select, insert, update, delete). Here's a sample from one of the models that I have:

```<code>function register_user($user_login, $user_profile, $department, $role) {

    $department_id = $this->get_department_id($department);
    $role_id = $this->get_role_id($role);

    array_push($user_login, $department_id, $role_id);

    $this->db->query("INSERT INTO tbl_users SET username=?, hashed_password=?, salt=?, department_id=?, role_id=?", $user_login);
    $user_id = $this->db->insert_id();

        array_push($user_profile, $user_id);

    $this->db->query("
            INSERT INTO tbl_userprofile SET firstname=?,
            midname=?, lastname=?, user_id=?
        ", $user_profile);
}
</code>```

Controller - talks to the model, calls up the methods in the model which queries the database, supplies the data which the views will display(success alerts, error alerts, data from database), inherits a parent controller which checks if user is logged in. Here's a sample:

```<code>function create_user(){
    $this->load->helper('encryption/Bcrypt');
    $bcrypt = new Bcrypt(15);

     $user_data = array(
        'username' => 'Username', 'firstname' => 'Firstname',
        'middlename' => 'Middlename', 'lastname' => 'Lastname',
            'password' => 'Password', 'department' => 'Department',
            'role' => 'Role'
    );

    foreach ($user_data as $key => $value) {
        $this->form_validation->set_rules($key, $value, 'required|trim');
    }

    if ($this->form_validation->run() == FALSE) {
        $departments = $this->user_model->list_departments();
        $it_roles = $this->user_model->list_roles(1);
        $tc_roles = $this->user_model->list_roles(2);
        $assessor_roles = $this->user_model->list_roles(3);

        $data['data'] = array('departments' => $departments, 'it_roles' => $it_roles, 'tc_roles' => $tc_roles, 'assessor_roles' => $assessor_roles);

        $data['content'] = 'admin/create_user';

            parent::error_alert();
            $this->load->view($this->_at, $data);

        } else {
        $username = $this->input->post('username');
        $salt = $bcrypt->getSalt();
        $hashed_password = $bcrypt->hash($this->input->post('password'), $salt);
        $fname = $this->input->post('firstname');
        $mname = $this->input->post('middlename');
        $lname = $this->input->post('lastname');
        $department = $this->input->post('department');
        $role = $this->input->post('role');

            $user_login     = array($username, $hashed_password, $salt);
            $user_profile   = array($fname, $mname, $lname);
        $this->user_model->register_user($user_login, $user_profile, $department, $role);

        $data['content'] = 'admin/view_user';

            parent::success_alert(4, 'User Sucessfully Registered!', 'You may now login using your account');

        $data['data'] = array('username' => $username, 'fname' => $fname, 'mname' => $mname, 'lname' => $lname, 'department' => $department, 'role' => $role);
        $this->load->view($this->_at, $data);
    }

}
</code>```

Views - this is where I put html, css, and JavaScript code (form validation code for the current form, looping through the data supplied by controller, a few if statements to hide and show things depending on the data supplied by the controller).

```<code><!--User registration form-->
<form class="well min-form" method="post">
    <div class="form-heading">
        <h3>User Registration</h3>
    </div>

    <label for="username">Username</label>
    <input type="text" id="username" name="username" class="span3" autofocus>

    <label for="password">Password</label>
    <input type="password" id="password" name="password" class="span3">

    <label for="firstname">First name</label>
    <input type="text" id="firstname" name="firstname" class="span3">

    <label for="middlename">Middle name</label>
    <input type="text" id="middlename" name="middlename" class="span3">

    <label for="lastname">Last name</label>
    <input type="text" id="lastname" name="lastname" class="span3">

    <label for="department">Department</label>
    <input type="text" id="department" name="department" class="span3" list="list_departments">

    <datalist id="list_departments">
        <?php foreach ($data['departments'] as $row) { ?>
            <option data-id="<?php echo $row['department_id']; ?>" value="<?php echo $row['department']; ?>"><?php echo $row['department']; ?></option>
        <?php } ?>
    </datalist>

    <label for="role">Role</label>
    <input type="text" id="role" name="role" class="span3" list="">

    <datalist id="list_it">
        <?php foreach ($data['it_roles'] as $row) { ?>
            <option data-id="<?php echo $row['role_id']; ?>" value="<?php echo $row['role']; ?>"><?php echo $row['role']; ?></option>
        <?php } ?>
    </datalist>

    <datalist id="list_collection">
        <?php foreach ($data['tc_roles'] as $row) { ?>
            <option data-id="<?php echo $row['role_id']; ?>" value="<?php echo $row['role']; ?>"><?php echo $row['role']; ?></option>
        <?php } ?>
    </datalist>

    <datalist id="list_assessor">
        <?php foreach ($data['assessor_roles'] as $row) { ?>
            <option data-id="<?php echo $row['role_id']; ?>" value="<?php echo $row['role']; ?>"><?php echo $row['role']; ?></option>
        <?php } ?>
    </datalist>

    <p>
        <button type="submit" class="btn btn-success">Create User</button>
    </p>
</form>

<script>
    var departments = [];
    var roles = [];

    $('#list_departments option').each(function(i){
        departments[i] = $(this).val();
    });

    $('#list_it option').each(function(i){
        roles[roles.length + 1] = $(this).val();
    });

    $('#list_collection option').each(function(i){
        roles[roles.length + 1] = $(this).val();
    });

    $('#list_assessor option').each(function(i){
        roles[roles.length + 1] = $(this).val();
    });

    $('#department').blur(function(){

        var department = $.trim($(this).val());
        $('#role').attr('list', 'list_' + department);
    });

    var password = new LiveValidation('password');
    password.add(Validate.Presence);
    password.add(Validate.Length, {minimum: 10});
    $('input[type=text]').each(function(i){
        var field_id = $(this).attr('id');
        var field = new LiveValidation(field_id);
        field.add(Validate.Presence);
        if(field_id == 'department'){
            field.add(Validate.Inclusion, {within : departments});
        }
        else if(field_id == 'role'){
            field.add(Validate.Inclusion, {within : roles})
        }
    });
</script>
</code>```

The codes above are actually code from the application that I'm currently working on. I'm working on it alone so I don't really have someone to review my code for me and point out the wrong things in it so I'm posting it here in hopes that someone could point out the wrong things that I've done in here. I'm also looking for some guidelines in writing MVC code like what are the things that should be and shouldn't be included in views, models and controllers. How else can I improve the current code that I have right now.
I've written some really terrible code before(duplication of logic, etc.) that's why I want to improve my code so that I can easily maintain it in the future.
Thanks!

答:
There are some series of Q&A on how to use mvc pattern in php.
Here is a nice answer on MVC details for PHP application - How should a model be structured in MVC?

Another list of posts that might be helpful too:

Write your own PHP MVC Framework

PHP MVC from the scratch - How to connect these classes?

Understanding MVC

Custom MVC Framework: How set links in view files

How do you use the MVC paradigm in PHP with ADODB as your DAL?

Title: How to do MVC the right way


答:
So in fact you just want an object oriented wrapper around a C API and it is still possible that an other object using this object calls its methods in an inappropriate way? Many OO languages including Python (although I'm not an expert at it) support the concept of exceptions for this. Consider something like throwing an InvalidStateException if the client code calls a method that is invalid in the current state.

If you want to prevent multiple instances of this object you can implement the Singleton design pattern.

Title: Constructs for wrapping a hardware state machine

Body:
I am using a piece of hardware with a well defined C API. The hardware is stateful, with the relevant API calls needing to be in the correct order for the hardware to work properly. The API calls themselves will always return, passing back a flag that advises whether the call was successful, or if not, why not. The hardware will not be left in some ill defined state. In effect, the API calls advise indirectly of the current state of the hardware if the state is not correct to perform a given operation. It seems to be a pretty common hardware API style.

My question is this: Is there a well established design pattern for wrapping such a hardware state machine in a high level language, such that consistency is maintained?

My development is in Python. I ideally wish the hardware state machine to be abstracted to a much simpler state machine and wrapped in an object that represents the hardware. I'm not sure what should happen if an attempt is made to create multiple objects representing the same piece of hardware.

I apologies for the slight vagueness, I'm not very knowledgeable in this area and so am fishing for assistance of the description as well!


答:
I'm a bit of a purist, I think. To me, models should contain all the logic required to interact with the data model, while the controller should contain the business logic, manipulate the data, and then pass the data to the views. Views should not contain any real logic - although I think display logic (e.g. should this user see this button with label A or label B?) is ok.

So far, the best example I have found of this is in the Yii Framework. Joomla, while purporting to use MVC, generally has very thin controllers and fat models - too much of the actual processing happens in the model when it should be in the controller.

In the end, the logic has to go where it fits best. I do occasionally find myself putting logic that is not strictly data interaction into the model, but usually this is a static function that I need to call from several other controllers. In this case, I feel the DRY principle outranks the pure MVC structure. Sometimes there is this balancing act, and ultimately it's the programmer's call on what goes where.

Title: How to do MVC the right way

Body:
I've been doing MVC for a few months now using the CodeIgniter framework in PHP but I still don't know if I'm really doing things right.

What I currently do is:

Model - this is where I put database queries (select, insert, update, delete). Here's a sample from one of the models that I have:

```<code>function register_user($user_login, $user_profile, $department, $role) {

    $department_id = $this->get_department_id($department);
    $role_id = $this->get_role_id($role);

    array_push($user_login, $department_id, $role_id);

    $this->db->query("INSERT INTO tbl_users SET username=?, hashed_password=?, salt=?, department_id=?, role_id=?", $user_login);
    $user_id = $this->db->insert_id();

        array_push($user_profile, $user_id);

    $this->db->query("
            INSERT INTO tbl_userprofile SET firstname=?,
            midname=?, lastname=?, user_id=?
        ", $user_profile);
}
</code>```

Controller - talks to the model, calls up the methods in the model which queries the database, supplies the data which the views will display(success alerts, error alerts, data from database), inherits a parent controller which checks if user is logged in. Here's a sample:

```<code>function create_user(){
    $this->load->helper('encryption/Bcrypt');
    $bcrypt = new Bcrypt(15);

     $user_data = array(
        'username' => 'Username', 'firstname' => 'Firstname',
        'middlename' => 'Middlename', 'lastname' => 'Lastname',
            'password' => 'Password', 'department' => 'Department',
            'role' => 'Role'
    );

    foreach ($user_data as $key => $value) {
        $this->form_validation->set_rules($key, $value, 'required|trim');
    }

    if ($this->form_validation->run() == FALSE) {
        $departments = $this->user_model->list_departments();
        $it_roles = $this->user_model->list_roles(1);
        $tc_roles = $this->user_model->list_roles(2);
        $assessor_roles = $this->user_model->list_roles(3);

        $data['data'] = array('departments' => $departments, 'it_roles' => $it_roles, 'tc_roles' => $tc_roles, 'assessor_roles' => $assessor_roles);

        $data['content'] = 'admin/create_user';

            parent::error_alert();
            $this->load->view($this->_at, $data);

        } else {
        $username = $this->input->post('username');
        $salt = $bcrypt->getSalt();
        $hashed_password = $bcrypt->hash($this->input->post('password'), $salt);
        $fname = $this->input->post('firstname');
        $mname = $this->input->post('middlename');
        $lname = $this->input->post('lastname');
        $department = $this->input->post('department');
        $role = $this->input->post('role');

            $user_login     = array($username, $hashed_password, $salt);
            $user_profile   = array($fname, $mname, $lname);
        $this->user_model->register_user($user_login, $user_profile, $department, $role);

        $data['content'] = 'admin/view_user';

            parent::success_alert(4, 'User Sucessfully Registered!', 'You may now login using your account');

        $data['data'] = array('username' => $username, 'fname' => $fname, 'mname' => $mname, 'lname' => $lname, 'department' => $department, 'role' => $role);
        $this->load->view($this->_at, $data);
    }

}
</code>```

Views - this is where I put html, css, and JavaScript code (form validation code for the current form, looping through the data supplied by controller, a few if statements to hide and show things depending on the data supplied by the controller).

```<code><!--User registration form-->
<form class="well min-form" method="post">
    <div class="form-heading">
        <h3>User Registration</h3>
    </div>

    <label for="username">Username</label>
    <input type="text" id="username" name="username" class="span3" autofocus>

    <label for="password">Password</label>
    <input type="password" id="password" name="password" class="span3">

    <label for="firstname">First name</label>
    <input type="text" id="firstname" name="firstname" class="span3">

    <label for="middlename">Middle name</label>
    <input type="text" id="middlename" name="middlename" class="span3">

    <label for="lastname">Last name</label>
    <input type="text" id="lastname" name="lastname" class="span3">

    <label for="department">Department</label>
    <input type="text" id="department" name="department" class="span3" list="list_departments">

    <datalist id="list_departments">
        <?php foreach ($data['departments'] as $row) { ?>
            <option data-id="<?php echo $row['department_id']; ?>" value="<?php echo $row['department']; ?>"><?php echo $row['department']; ?></option>
        <?php } ?>
    </datalist>

    <label for="role">Role</label>
    <input type="text" id="role" name="role" class="span3" list="">

    <datalist id="list_it">
        <?php foreach ($data['it_roles'] as $row) { ?>
            <option data-id="<?php echo $row['role_id']; ?>" value="<?php echo $row['role']; ?>"><?php echo $row['role']; ?></option>
        <?php } ?>
    </datalist>

    <datalist id="list_collection">
        <?php foreach ($data['tc_roles'] as $row) { ?>
            <option data-id="<?php echo $row['role_id']; ?>" value="<?php echo $row['role']; ?>"><?php echo $row['role']; ?></option>
        <?php } ?>
    </datalist>

    <datalist id="list_assessor">
        <?php foreach ($data['assessor_roles'] as $row) { ?>
            <option data-id="<?php echo $row['role_id']; ?>" value="<?php echo $row['role']; ?>"><?php echo $row['role']; ?></option>
        <?php } ?>
    </datalist>

    <p>
        <button type="submit" class="btn btn-success">Create User</button>
    </p>
</form>

<script>
    var departments = [];
    var roles = [];

    $('#list_departments option').each(function(i){
        departments[i] = $(this).val();
    });

    $('#list_it option').each(function(i){
        roles[roles.length + 1] = $(this).val();
    });

    $('#list_collection option').each(function(i){
        roles[roles.length + 1] = $(this).val();
    });

    $('#list_assessor option').each(function(i){
        roles[roles.length + 1] = $(this).val();
    });

    $('#department').blur(function(){

        var department = $.trim($(this).val());
        $('#role').attr('list', 'list_' + department);
    });

    var password = new LiveValidation('password');
    password.add(Validate.Presence);
    password.add(Validate.Length, {minimum: 10});
    $('input[type=text]').each(function(i){
        var field_id = $(this).attr('id');
        var field = new LiveValidation(field_id);
        field.add(Validate.Presence);
        if(field_id == 'department'){
            field.add(Validate.Inclusion, {within : departments});
        }
        else if(field_id == 'role'){
            field.add(Validate.Inclusion, {within : roles})
        }
    });
</script>
</code>```

The codes above are actually code from the application that I'm currently working on. I'm working on it alone so I don't really have someone to review my code for me and point out the wrong things in it so I'm posting it here in hopes that someone could point out the wrong things that I've done in here. I'm also looking for some guidelines in writing MVC code like what are the things that should be and shouldn't be included in views, models and controllers. How else can I improve the current code that I have right now.
I've written some really terrible code before(duplication of logic, etc.) that's why I want to improve my code so that I can easily maintain it in the future.
Thanks!


问:
Am I too young to burn out?
I feel like I have burned out, even though I am only out of college for 5 years.

For the first 3 years of my career, things were going awesome. I was never anything special in school, but I felt special at my company. Looking back, I could tell that I made all the right moves:

I actively tried to improve myself daily.

I made a point of helping anyone I could.

I made a point (and read books about) being a good team member.

I had fun.

After 3 years in a row as being rated as a top employee, I converted that political capital into choosing to work on an interesting, glamorous project with only 2 developers: me and a highly respected senior technical leader.

I worked HARD on that project, and it came out a huge success. High in quality, low in bugs, no delays, etc.

The senior tech lead got a major promotion and a GIGANTIC bonus. I got nothing.

I was so disappointed that I just stopped caring. Over the last year, I have just kind of floated. During my first 4 years I felt energized after a 10 hour day. Now I can barely be bothered to work 6 hours a day.

Any advice? I don't even know what I'm asking. I am just hoping smart people see this and drop me a few pieces of wisdom.

答:
Funks come and go. Oddly enough, every time I have found myself in a similar mood, it was also because I didn't feel that my work was appreciated. Once, I didn't get a raise that I thought I should have received and a bonus was less than I was expecting. It took me a year to get over that. I don't think the solution is necessarily to find a new job. Just keep working hard, it will pass. I promise it will pass.

In my case, I actually went out and found a new job, and my current company gave me about a 45% raise and a nice bonus to stay. That helped out quite a bit. My best advice is not necessarily to move - it may be best to keep working where you are and see what happens. If it doesn't improve, why not find another offer and give them an opportunity to counter it? You may be surprised at how much they actually value you. If they don't, then just take the kick in the balls and go to the new job - you only have your pride to lose and it is usually a good exercise to be humbled every now and then.

Title: Am I too young to burn out?


问:
Database ERD design: 2 types user in one table
I have read this (Database design: 3 types of users, separate or one table?)

I decided to put admin and normal user in one table since the attributes are similar:

```<code>fullname,
address,
phone,
email,
gender
...
</code>```

Then I want to draw ERD, suddenly my mind pop out a question. How to draw?
Customer make appointment and admin approve appointment. now only two tables, and admin, customer in same table. Help.

答:
That's what I'd do:

```<code>table user (
  id primary key,
  name,
  email,
  -- etc
);

table approver (
  id primary key foreign key user(id),
  appointed_date,
  -- etc
);

table appointment (
  -- whatever PK
  created_by foreign key user(id),
  approved_by foreign key approver(id),
  -- etc
);
</code>```

Now any user can create an appointment, but only users also present in approver table can approve it.

Body:
That's what I'd do:

table user (
  id primary key,
  name,
  email,
  -- etc
);

table approver (
  id primary key foreign key user(id),
  appointed_date,
  -- etc
);

table appointment (
  -- whatever PK
  created_by foreign key user(id),
  approved_by foreign key approver(id),
  -- etc
);

Now any user can create an appointment, but only users also present in approver table can approve it.


答: I'm my career I've found that raises and bonuses are great...for a while. But if the work and the people don't interest you then you will ultimately dislike the job. I would sit down with your manager and tell him/her what you felt when you weren't recognized for your accomplishments. Some mangers and companies are just awful at this and need to be prodded a little. Don't be embarrassed to fight for yourself. At the end of the day your biggest supporter needs to be yourself!</p>

Title: Am I too young to burn out?

Body:
I feel like I have burned out, even though I am only out of college for 5 years.

For the first 3 years of my career, things were going awesome. I was never anything special in school, but I felt special at my company. Looking back, I could tell that I made all the right moves:

I actively tried to improve myself daily.

I made a point of helping anyone I could.

I made a point (and read books about) being a good team member.

I had fun.

After 3 years in a row as being rated as a top employee, I converted that political capital into choosing to work on an interesting, glamorous project with only 2 developers: me and a highly respected senior technical leader.

I worked HARD on that project, and it came out a huge success. High in quality, low in bugs, no delays, etc.

The senior tech lead got a major promotion and a GIGANTIC bonus. I got nothing.

I was so disappointed that I just stopped caring. Over the last year, I have just kind of floated. During my first 4 years I felt energized after a 10 hour day. Now I can barely be bothered to work 6 hours a day.

Any advice? I don't even know what I'm asking. I am just hoping smart people see this and drop me a few pieces of wisdom.


答:
I want to draw ERD

You need to clearly specify whether a normal user can be an admin one day or not. However, we don't know from your description. This is a key point.

If a regular user will never be an admin you better use 2 different tables. If you want to use 1 table here are 2 solutions. The first uses the subtype concept which requires at least 1 different column between the two tables or that a subtype is a child table.

The data you provided does not show any different attributes between the two types of users, so you can't use the first solution based on the data given.

The second solution is more generic. If you plan to have the
RegularUser and admin changing types/roles, then you need to create an m-m relationship between RegularUser and UserType. (Note AppointmentID is PK for Appointment table).

Title: Database ERD design: 2 types user in one table

Body:
I have read this (Database design: 3 types of users, separate or one table?)

I decided to put admin and normal user in one table since the attributes are similar:

```<code>fullname,
address,
phone,
email,
gender
...
</code>```

Then I want to draw ERD, suddenly my mind pop out a question. How to draw?
Customer make appointment and admin approve appointment. now only two tables, and admin, customer in same table. Help.


答:
That's not burnout, that's letdown.

Go talk to your boss. Cite your stellar performance record. Ask for a raise and a promotion. If he/she asks about your recent lackluster performance (if it has even been noticed!), be honest: you felt so let down and overlooked after the last big project that you've been demoralized, and have decided to ask for the recognition and reward that you think you deserve to repair the damage.

All he/she can do is say no. Technically he/she can also fire you, but at this point I doubt that you'd care a whole lot about that, it might even be a relief.

But first, look at stackoverflow.com/jobs to see what else is out there for you.

And, as always, don't take career advice from random strangers on the Internet ;)

And good luck!

Title: Am I too young to burn out?


答:
I think this is not burnout, but disappointment, also can be an important experience.

You show a very deep interest in computing and self improvement. This is a great and rare gift that you had, and also have it "somewhere" today. On the other hand, you can't "sell" this gift well (which I feel very close to my problems with this world anyway ;-) ), and rare managers are willing to pay for something that they can get for free ;-) . Yours were none of that kind.

You used this gift for three years and with success, under a good lead - you have gained tons of experience, and confidence, because you "know how you have done" many things, compared to lots of colleagues who "think how it should be done". This is the true value of that time, which can't be taken away from you - but of course you can choose not to use it. This is what you have done for the last one year and that makes you feel "burned out" today.

About the money. Many people would pay a lot for your experience - others would earn a lot for the job you have done. You are in the middle: got the experience for free - got no bonus for the result. Oops, I have almost forgotten: you were payed as an employee, and the management considered that this was a fair business. (You are young, and perhaps have not worked hard for months for a company that gone bankrupt and payed nothing, as I have. Sh*t happens.)

So, the lesson. You felt the management had made a bad decision: evaluated your contribution to the successful project as your duty for your salary. Have you asked them about this? Or your senior partner? Or just waited for the bonus? If you want something, or feel something unfair, ASK!

Of course you should not forget that you have your reasons, and they have their reasons - so maybe it is not beneficial to say: "you owe me a bonus" - if they felt so, you would have gotten it. But go and explain your devotion, your results, and that you have problem with the situation. You have to negotiate. This is business, and all is about the revenue. If they feel you are important for them, they care for this - if not, then they refuse your request (which is also NOT a disaster, just a feedback that you can learn from).

The problem here is the time. You had a position and reputation when you should have asked, but wasted a year, and moaning will not take it back. However: you were not fired, still get the same money for doing the third of what you have done - you will learn that this is not that bad at all... :-)

My advice: don't complain, get back on your feet again. If you are in good relationship, talk through this whole story with that senior. I don't think it is the best time for you to go to the management for any bonus - but you have a lot of time ahead that you should not waste. Focus on the experience you have, go for the next tasks with that power. Realize that you have not worked that hard for the money, but for the quest (should read about Motivation 3.0). And your current problem may not be the lack of bonus, but the fear that your work was not that honorable as you feel. Don't be so shy next time: at least you will have an answer to digest, not just hunger.

A must see: the Last lecture from Randy Pausch. Quote: "Don't complain, just try harder!" (from the first black baseball player, who had in his contract that he should not complain about being spit on by the crowd... just for the contrast).

Cheers! :-)

Title: Am I too young to burn out?


答:
It Happens

Unfortunately we don't always get the credit we deserve, or management will give credit to the people directly under them, who do not necessarily have the power (or honesty) to bestow some of it upon you. It's an organizational thing: by way of the organigram, it should trickle down; except a few people act as dams.

I'm afraid that's what happened to you. Most likely, that senior tech did deserve a bonus and promotion, but you were too much below the radar for the people above.

Basically, this happened:

Market Yourself

It's not because you already have a job that you should stop selling yourself.

Ask for a Raise!!!

People have a hard-time understanding this: they won't come to you naturally.

And if they do, it's either one of these 2 cases:

they emit raises to have control over the increases, not you (you feel happy and recognized, you don't need to request one, and would feel bad about asking more).

you work in the most awesome company ever created (please send me the address).

Do ask for a raise. Learn to keep track of what you do. Keep track of bug countrs, commit logs, real achievements. Cover your ass is a real rule in the world.

Request a raise means different things:

"I want more money and am greedy"

Except that's what you think first, but it's not necessarily what they think first.

"I want what I deserve, or I'll get it somewhere else"

If you ask for a raise, it means you are conscious that there is something better out there.

"I am unhappy"

And the obvious implication is that you will not perform as well.

Asking for a raise implies a status change. You get more money, but also more scrutiny. People will look to make sure that you deserved it, after the fact. Be prepared for this as well.

Your position in a company is a fluid thing: it changes and evoles. Take control of that and don't just let things happen.

Raise the Issue

You mention your boss... how come he didn't notice this issue? Or did he, but didn't do anything about it? It's his reponsibility to make sure the work of his subordinates his well-advertised and respected.

If he's unaware of your problem, talk it over with him. Make it clear that this is an issue, that it affected you.

Make you'll come across as a diva (maybe you are, for all I know), but IT DOESN'T MATTER. What matters is that your boss will notice that one of his employees is unhappy, and that it is a problem for him and others.

Look for Alternatives

You're young, you're employable, and you're good.

Why would you think you need to stay where you are? Maybe this was just your first experience, and opportunity to make your teeth on something. Now, you can go out and reach for more.

It's sometimes easier to get a career break by actually taking a career break, in one sense. So look for other jobs, brush over your resume, sell yourself well, and attempt to reach for the next job slightly up the ladder that you are interested in. And state your salary expectations (well, advertise higher than your salary expectations, actually) to agencies.

Be careful about your privacy. It's best, at this stage, that nobody in your company knows that you are looking. But if they call you up on it, then so what? It also shows that there's an issue and they need to address it, or things will change. They can't control that.

Basically, it allows you to do this:

Keep it Professional, and Civil - Don't Burn Bridges

DO NOT whine.

DO NOT get too passionate.

DO NOT get personal.

DO stay professional.

DO stay polite.

These are professional, business relationships. You will most likely need references from your current company when you decide to go somewhere else. Do not burn bridges.

Or, this will happen:

(Unlikely though, as that would mean your boss tries to keep you while knowingly making you unhappy... Surely, he'd know no good can come from that. Or run for the hills, now!)

About Burn-Out

I haven't actually addressed this...

While it doesn't sound to me like you've burned out and are simply demotivated, I would say that there no age requirement or limit to burn out. It can happen at 23 like it can at 77. The good thing is that you can recover from it at 23 and look past it. It's harder at 45, for instance, to look for alternatives.

Don't overwork yourself. Don't do jobs for extended periods of time that suck the life and the joy of programming out of you. It doesn't seem like you were using these, so I doubt you actually burned out.

You were burned, but in a different way. Consider it just being a lesson. Now get back to work, get that raise or recognition, and remember to have fun coding. And if it's tough at the moment to have fun doing it, I'd even advise to pick up small projects that make it fun at the workplace (develop a tool to make something easier, something like this).

Pictures are courtesy of Dilbert.com and Scott Adams.

Title: Am I too young to burn out?


答:
It happens, it sucks but it happens. I would talk to your boss or his boss about it.

In addition I would try to take steps to re-find the passion, get involved in a local meetup and maybe give a few talks, or find a hackathon to go to. If nothing else when you do decide to make the jump it will help if your name is known around town.

It might also be worth while to spend some time on non work stuff. Start running or take up a hobby, join the local theater group etc. To broaden your life and let you get your head out of work for a while

Title: Am I too young to burn out?


问:
What is an effective git process for managing our central code library?
Quick background: we're a small web agency (3-6 developers at any one time) developing small to medium sized Symfony 1.4 sites. We've used git for a year now, but have previously used Subversion.

For the past 6 months we've put a lot of development time into a central Symfony plugin that powers our custom CMS.  This plugin includes a number of features, helpers, base classes etc. that we use to build custom functionality. This plugin is stored in git, but branches wildly as the plugin is used in various products and is pulled from/pushed to constantly.  The repository is usually used as a submodule within a major project.

The problems we're starting to see now are a large number of Merge conflicts and backwards incompatible changes brought into the repository by developers adding custom functionality in the context of their own project.

I've read Vincent Driessen's excellent git branching model and successfully used it for projects in the past, but it doesn't seem to quite apply well to our particular situation; we have a number of projects concurrently using the same core plugin while developing new features for it.

What we need is a strategy that provides the following:

A methodology for developing major features within the code repository.

A way of migrating those features into other projects.

A way of versioning the core repository, and of tracking which version each major project uses.

A plan for migrating bug fixes back to older versions.

A cleaner history that's easier to see where changes have come from.

Any suggestions or discussion would be greatly appreciated.

答:
Shared code is more expensive to develop and maintain.  It has to work in multiple scenarios; it must be backward compatible; and it should have test cases to ensure changes do not break existing clients.

As a general rule, shared functionality is worth it only if it's used in three or more places.

```<code>developers adding custom functionality in the context of their own project.
</code>```

A custom change for one or two projects should not make it into the shared code.  If you allow this, the shared code will quickly increase in complexity, up to a point where it becomes impossible to maintain.  No workflow can help against that.

Body:
Shared code is more expensive to develop and maintain.  It has to work in multiple scenarios; it must be backward compatible; and it should have test cases to ensure changes do not break existing clients.

As a general rule, shared functionality is worth it only if it's used in three or more places.

developers adding custom functionality in the context of their own project.

A custom change for one or two projects should not make it into the shared code.  If you allow this, the shared code will quickly increase in complexity, up to a point where it becomes impossible to maintain.  No workflow can help against that.


答:
Well, been there, done that, got the t-shirt but nothing else.

Simple answer : change company and let them roll without you : you'll earn more, have new challenges, meet new guys. When internal stuff ain't doing the trick, check another meadow.

Just keep in mind that you'll have to regrow a reputation, invest time, but it's worth it (just changed after 6 yrs in same company, got 10yrs of XP)

Title: Am I too young to burn out?


答:
I feel your pain as I deal with this sort of thing every day. My situation is having to maintain multiple customer versions of an open source project, each with a different selection of plugins, core hacks, etc. It's not fun when you have 50 of them.

I've not yet found an ideal (perfectly clean) solution, but my modifications to GitFlow are:

Make a separate branch (other than master) for each customer's production code. Use master for the definitive all-features version, and only merge what the customer wants into their own ones.

Keep developments (or added plugins etc) on tightly defined hotfix and feature branches, and leave them in place, even once merged, so you can merge into other customer branches if you need to. This also makes it easy to keep track of who has what features by crunching through the logs.

When developing new features, branch from the latest common ancestor of all customers if possible. This means that you will be able to merge into develop and then master, but also merge into the customer production branches without (in theory) causing conflicts.

Have one main repo just for development work, which looks like GitFlow. Have another that has your dev repo as a remote, which is used to store customer branches so that your dev repo has a clean(er) history.

If you really can't resolve a conflict easily and need to cherry-pick a whole branch at once, use rebase --onto like this. Just make sure it's clear in the commit messages where the feature cam from and why it's not been merged normally.

Using git has had an added side benefit in that we can now run a cron job across all the production servers which checks for unstaged files in the git repos. We now know if the support staff have been dicking about with the production code on the servers without telling anyone, which has prevented a lot of headaches :)

Hope that helps.

Title: What is an effective git process for managing our central code library?

Body:
Quick background: we're a small web agency (3-6 developers at any one time) developing small to medium sized Symfony 1.4 sites. We've used git for a year now, but have previously used Subversion.

For the past 6 months we've put a lot of development time into a central Symfony plugin that powers our custom CMS.  This plugin includes a number of features, helpers, base classes etc. that we use to build custom functionality. This plugin is stored in git, but branches wildly as the plugin is used in various products and is pulled from/pushed to constantly.  The repository is usually used as a submodule within a major project.

The problems we're starting to see now are a large number of Merge conflicts and backwards incompatible changes brought into the repository by developers adding custom functionality in the context of their own project.

I've read Vincent Driessen's excellent git branching model and successfully used it for projects in the past, but it doesn't seem to quite apply well to our particular situation; we have a number of projects concurrently using the same core plugin while developing new features for it.

What we need is a strategy that provides the following:

A methodology for developing major features within the code repository.

A way of migrating those features into other projects.

A way of versioning the core repository, and of tracking which version each major project uses.

A plan for migrating bug fixes back to older versions.

A cleaner history that's easier to see where changes have come from.

Any suggestions or discussion would be greatly appreciated.


答:
Scott Berkun has some things to say - and they're very good things too.

On surviving creative burnout, he says:

Even with the most calculating and evil manager, if you report to them
  you’re an asset to them. When you’re toasty, you’re at risk of
  crashing completely and become entirely useless.

So even if they see you as a yuppified form of urban cattle, they want
  you producing and creating over the long haul. If they can convert
  weeks of malaise and crappy work into a handful of days, it’s entirely
  in their interest to do so. It’s pure economics. A more likely
  situation is that, if your manager is paying any attention at all,
  they already know there’s something wrong. They can sense the
  difference in your behavior in meetings, and see the quality or
  precision of the work you’re producing. A good manager would ask and
  investigate to find out what’s wrong (it’s their job), but some don’t
  know what to say. In that case, it’s up to you.

Here’s an easy way to go: “Hey boss. I’m concerned about something. I
  haven’t been as motivated as I’d like on this project for the last 2
  weeks. I’m trying to figure out why, and it’s possible I’m burnt out
  on some aspect of this work. If you have suggestions for me, I’m open
  to them, but I just wanted to make sure you were aware of what’s going
  on. I’ll keep you posted as I figure out what we can do about it.” By
  starting a conversation like this, you take responsibility for you
  burnout. You score points with you manager (and with yourself) for be
  aware of what’s going on, and taking a mature and open course of
  action about it.

Now, he's talking about times when you're just losing the will to bother, your case is a bit more extreme but the points still stand: take a mature attitude to this. You may feel depressed but no-one will give much of a fig unless you at least start to help yourself. So see your manager and point out the unfairness of it all (not in a whiny way, of course, but in a responsible "I want to be a more productive asset to you" kind of way) which should bring him onto your side of things a little. Then you are in a decent position to get a bonus for yourself and to start a ball of promotion and general manager-is-aware-of-you rolling uphill. (god, I sound like a marketing manager!)

In short - try to overcome your feelings of depression and get dealing with the situation in as professional a manner as possible. If it fails, you were going to tell them to stick it anyway, so you lose nothing. If it succeeds, all well and good. The only bad thing you can do here is to dwell on it and stew in your own juices.

Title: Am I too young to burn out?


问:
What came first, the compiler, or the source?
I'm curious about the birth of the compiler.  How did programming begin?  Did people first build hardware that recognized a certain set of commands, or did people define a language and then build hardware around it?  And on a related note, what was the first programming language?</p>

答:
The compiler was first. It was directly written in machine code, for the source could not be compiled without a compiler.

Wikipedia articles like this one about Computer Languages can answer most of the questions. If not, just pick one of the books by Tanenbaum, like Structured Computer Organization , which can answer more questions than you can even ask :)

I can not say anything more specific, for your question is too broad.


答:
There are different ways to react to disappointment, and an attitude of "not caring" is not a good one.
It is hard when you are wondering to yourself what difference does it make whether you do a good job of not. That is demotivating and a lot of people respond that way. But the key question you need to ask yourself is what is your investment for the future? If you are not on top of your game, then that would affect your ability in giving good answers to questions at interviews? Alternatively if you decide to stay where you are, you might get passed over for promotion, thus deprieving yourself of the massive bonuses you missed out on. It doesn't matter who you work for, always be on top of your game. You need to be these days.</p>

Title: Am I too young to burn out?


问:
Should I expose IObservable<T> on my interfaces?
My colleague and I have dispute. We are writing a .NET application that processes massive amounts of data. It receives data elements, groups subsets of them into blocks according to some criterion and processes those blocks.

Let's say we have data items of type Foo arriving some source (from the network, for example) one by one. We wish to gather subsets of related objects of type Foo, construct an object of type Bar from each such subset and process objects of type Bar.

One of us suggested the following design. Its main theme is exposing IObservable objects directly from the interfaces of our components.

```<code>// ********* Interfaces **********
interface IFooSource
{
    // this is the event-stream of objects of type Foo
    IObservable<Foo> FooArrivals { get; }
}

interface IBarSource
{
    // this is the event-stream of objects of type Bar
    IObservable<Bar> BarArrivals { get; }
}

/ ********* Implementations *********
class FooSource : IFooSource
{
    // Here we put logic that receives Foo objects from the network and publishes them to the FooArrivals event stream.
}

class FooSubsetsToBarConverter : IBarSource
{
    IFooSource fooSource;

    IObservable<Bar> BarArrivals
    {
        get
        {
            // Do some fancy Rx operators on fooSource.FooArrivals, like Buffer, Window, Join and others and return IObservable<Bar>
        }
    }
}

// this class will subscribe to the bar source and do processing
class BarsProcessor
{
    BarsProcessor(IBarSource barSource);
    void Subscribe();
}

// ******************* Main ************************
class Program
{
    public static void Main(string[] args)
    {
        var fooSource = FooSourceFactory.Create();
        var barsProcessor = BarsProcessorFactory.Create(fooSource) // this will create FooSubsetToBarConverter and BarsProcessor

        barsProcessor.Subscribe();
        fooSource.Run(); // this enters a loop of listening for Foo objects from the network and notifying about their arrival.
    }
}
</code>```

The other suggested another design that its main theme is using our own publisher/subscriber interfaces and using Rx inside the implementations only when needed.

```<code>//********** interfaces *********

interface IPublisher<T>
{
    void Subscribe(ISubscriber<T> subscriber);
}

interface ISubscriber<T>
{
    Action<T> Callback { get; }
}

//********** implementations *********

class FooSource : IPublisher<Foo>
{
    public void Subscribe(ISubscriber<Foo> subscriber) { /* ...  */ }

    // here we put logic that receives Foo objects from some source (the network?) publishes them to the registered subscribers
}

class FooSubsetsToBarConverter  : ISubscriber<Foo>, IPublisher<Bar>
{
    void Callback(Foo foo)
    {
        // here we put logic that aggregates Foo objects and publishes Bars when we have received a subset of Foos that match our criteria
        // maybe we use Rx here internally.
    }

    public void Subscribe(ISubscriber<Bar> subscriber) { /* ...  */ }
}

class BarsProcessor : ISubscriber<Bar>
{
    void Callback(Bar bar)
    {
        // here we put code that processes Bar objects
    }
}

//********** program *********
class Program
{
    public static void Main(string[] args)
    {
        var fooSource = fooSourceFactory.Create();
        var barsProcessor = barsProcessorFactory.Create(fooSource) // this will create BarsProcessor and perform all the necessary subscriptions

        fooSource.Run();  // this enters a loop of listening for Foo objects from the network and notifying about their arrival.
    }
}
</code>```

Which one do you think is better? Exposing IObservable and making our components create new event streams from Rx operators, or defining our own publisher/subscriber interfaces and using Rx internally if needed?

Here are some things to consider about the designs:

In the first design the consumer of our interfaces has the whole power of Rx at his/her fingertips and can perform any Rx operators. One of us claims this is an advantage and the other claims that this is a drawback.

The second design allows us to use any publisher/subscriber architecture under the hood. The first design ties us to Rx.

If we wish to use the power of Rx, it requires more work in the second design because we need to translate the custom publisher/subscriber implementation to Rx and back. It requires writing glue code for every class that wishes to do some event processing.

答:
I think saying that IObservable<T> ties you to Rx is the same as saying that IEnumerable<T> ties you to LINQ. Yes, IObservable<T> is at the core of Rx and Rx lets you do a lot of things with IObservable<T>.

But that doesn't mean you have to use Rx to implement your classes, even if they inherit from IObservable<T>. And you also don't have to use Rx to work with the class, you could directly use Subscribe(). I believe this is also the reason why IObservable<T> is included in the core of the framework (it's in mscorlib since .Net 4), but Rx isn't.

So, unless IObservable<T> doesn't fit your needs, you should use it. On the plus side, you'll get the possibility to use Rx. On the negative side, you might need to wrap your implementation to make it look like IObservable<T>, if you decide to change the implementation later on. But you would have to do the same if you used a custom interface.

IObservable<T> is just an interface, it doesn't tie you up to anything. But it gives you the ability to use libraries that already work with it, unlike a custom interface.


问:
How can test users access an unpublished iOS app?
I am considering outsourcing the development of an iOS app to various independent developers. I will have have various testers of the app. We all work for separate companies. Some of these testers will be customers, who I would like feedback from. As there are multiple developers involved I expect there to be a new release on a daily basis.

How can this be done? Would each of the testers need to buy some sort of license to avoid having to go through the app approval process? Is there any smooth way to do this so that it will not be a hassle for our friendly customers, who are willing to test our app?

答: It seems like what I am after is Ad Hoc Distribution, which is limited to 100 users.</p>


问:
Using EC2 instance as main development platform
My problem

I am working as a consultant for various companies. Each company provides me with a laptop with their software on and I also have my own, where I have my development environment. I tend to buy a new laptop every second year and find myself spending lots of time configuring and installing software. I also spend a lot of time waiting for my laptop to process things.

To solve all these issues, I am now considering using EC2 (running windows instances) as my main development platform and just access this from any PC I happen to be at. I calculated that running the Large instance (cheapest 64-bit) for 8 hours a day for a year costs me 960$ per year, which is acceptable.

I imagine that when I approach the workplace each day, I will make a single tap on my phone to fire up the instance, so it is ready when I get to work. I should have different icons on my phone to fire up the various instance types. The same software should of course automatically be loaded on the various hardware (sometimes I would even need their instance with 68.4 GB of memory).

Another advantage is that if I am having a specific problem with my instance, I could fire up another instance and have someone look into the problem and update the image.

My question:

Does anyone have experience with such a setup on EC2? What kind of problems do you foresee?

答:
I'm using EC2 micro instances via the free tier and it's fantastic.  It's fast, responsive, and I hardly have to pay a dime.  It lasts for about a year, but if you need a temporary development environment, EC2 is the way to go.  I've had nothing but great experiences on there.  Micro instances for me have even supported traffic up to 100k hits a day (very well-handled too, at only a peak of about 70% CPU usage).

Take a look at bitnami - it's a quickstart LAMP stack (or any stack) image to get running in basically 5 minutes.  Also, make sure you configure your security correctly!  Only allow SSH, HTTP/HTTPS connections in your web security groups.  Use SFTP for file transfer.


答:
Programming began with people writing machine code directly into memory, onto punched cards and paper tape or even shorting links on a patch panel. Whether the hardware was built around the needs of the software or vice versa is difficult to tell. Certainly the earliest design for a turing complete programmable computer, Babbage's Analytical engine, pre-dated Ada Lovelace's first documented program.

As to the first programming language, I have argued that it was the machine language of Babbage's analytical engine (from the question What was the first programming language written for computers?)

To answer the question in your question title, since assembly language is source code, and assembly languages pre-date high level languages which could be compiled into assembler, the source code came first.

Also, a compiler has never been necessary, just convenient.

It is perfectly possible to write software directly into memory if you have memorised the appropriate op-code tables. In fact, some early computers required the user to punch in the bootstrap code on the front panel hex keypad to get them to boot, but you could tap in any code you liked and it would be run.

Admittedly as CPU's get more complex, this gets more difficult, but a simple instruction set like 6809, or Z80 (ignoring all the weird indexed modes) is relatively easy to program even without an assembler, let alone a compiler from a high level language.

If Babbage's analytical engine had ever been built, I'm sure there would have been a steampunk Mel, writing optimised programs directly onto loom cards.

Title: What came first, the compiler, or the source?

Body: I'm curious about the birth of the compiler.  How did programming begin?  Did people first build hardware that recognized a certain set of commands, or did people define a language and then build hardware around it?  And on a related note, what was the first programming language?</p>


答:
I'm using EC2 more traditionally, as servers. The problems I'd foresee with what you're attempting:

storage: You have two choices, persistent EBS and ephemeral storage. EBS is quite slow, can't really imagine working with an IDE using such a slow disk. Ephemeral storage goes away as soon as you stop your instance, so not quite good option either. And of course nowhere near as fast as SSD.

memory: not enough, especially given how cheap RAM is nowadays.

CPU: really, really under-powered, only 2 slow virtual cores. Entry level i3 will give you better performance, not to mention i5 or i7.

connectivity: latency to AWS is quite high, way above for what you'd expect. Given that I'm using EC2 instances in Europe while connecting from Europe I'd expect latency well below 30ms, meanwhile it's more like 300-500ms. For comparison transatlantic latency is about 50ms. Latency would make any interactive GUI environment unusable.

Overall, cloud for servers, it's huge advantage is scaling (especially auto-scaling). Which you're not going to use at all. Yet you're going to have to put up with all annoyances of the cloud.

UPDATE as of mid-2015: since I've written this answer in 2012, AWS has added SSD storage, reduced latency. As for CPU and RAM, it still holds, EC2 is seriously under-powered compared to an average laptop, unless you're willing to spend well in excess of $200/mo.

Title: Using EC2 instance as main development platform

Body:
My problem

I am working as a consultant for various companies. Each company provides me with a laptop with their software on and I also have my own, where I have my development environment. I tend to buy a new laptop every second year and find myself spending lots of time configuring and installing software. I also spend a lot of time waiting for my laptop to process things.

To solve all these issues, I am now considering using EC2 (running windows instances) as my main development platform and just access this from any PC I happen to be at. I calculated that running the Large instance (cheapest 64-bit) for 8 hours a day for a year costs me 960$ per year, which is acceptable.

I imagine that when I approach the workplace each day, I will make a single tap on my phone to fire up the instance, so it is ready when I get to work. I should have different icons on my phone to fire up the various instance types. The same software should of course automatically be loaded on the various hardware (sometimes I would even need their instance with 68.4 GB of memory).

Another advantage is that if I am having a specific problem with my instance, I could fire up another instance and have someone look into the problem and update the image.

My question:

Does anyone have experience with such a setup on EC2? What kind of problems do you foresee?


答: Take a look at TestFlight.  You'll enroll in the iOS developer program, have your testers set up their devices as members of your team and be able to push new builds to TestFlight.  Your testers will receive notifications and get the new builds to test.</p>

Title: How can test users access an unpublished iOS app?

Body:
I am considering outsourcing the development of an iOS app to various independent developers. I will have have various testers of the app. We all work for separate companies. Some of these testers will be customers, who I would like feedback from. As there are multiple developers involved I expect there to be a new release on a daily basis.

How can this be done? Would each of the testers need to buy some sort of license to avoid having to go through the app approval process? Is there any smooth way to do this so that it will not be a hassle for our friendly customers, who are willing to test our app?


问:
Why Browsers do not resolve simple known issues?
Why Browsers do not resolve simple known issues such as:

(in the context of CSS)

Do NOT start a class name with a number! This is only supported in Internet Explorer

and

Do NOT start an ID name with a number! It will not work in Mozilla/Firefox.

答:
These are not issues. This is the W3C standard.

Most good browsers try to follow standards as much as possible (Firefox, Chrome).

Some browser just doesn't care, or is trying to impose its own standard though (IE).


问:
In-memory DB to perform intersects on set slices
I have a specific programming need where I need to efficiently store large sorted sets in memory, query them for ranges, and intersect them against other sets that are also queried for ranged.

I am looking at Redis, but I can't see a range slice command. MongoDB can only use 1 index, so it has to perform row-level scans, whereas I wish to process using columns that are intersected.

I'm also looking at Counchbase, but can't easily determine from the documentation if it is suited to this. I know it uses Memcached, which is AFAIK not suited to this usage.

Could anyone share potential solutions for this specific problem?

EDIT
For example, I need to perform the following:

Get the IDs of all cars where the price is between 2000 and 3000, and intersect that will all cars where the engine capacity is between 3000 and 4000.

答:
Java provides Treemap.  In that language, I'd put the cars in one Map keyed by price and one keyed by engine size.  Pull the desired set from one of the "tables" and put it in an easily searchable collection.  (A TreeMap, TreeSet, or HashSet might do.)  Then scan the desired range of the other Treemap and see which of its cars are in your searchable collection.  (Or you could just run retainAll() against your searchable collection, passing it the desired subset of cars from the other collection.  But check that the Sun/Oracle code is as fast as anything you'd write.)

C# seems to have all the pieces to do this also.  Endless options, in fact.  (But it's harder to guess at efficiency.)  I'd expect other languages to have the same.  Whether they're better than Redis would be a question.  In fact, you might be able to use my Java Collections Framework tricks with Redis.

Note:  in memory, a straight linear search might not take too long, especially if the data is in an array, an array-based collection, or some kind of linked list.  It might not be worth it to get fancy.

You'll want to blend in the data structures you use for this solution with whatever else you're doing in memory.