212

I have been programming for some months now and a frequently used word is "context" in classes. Like ServletContext (Java), Activity (Android), Service (Java, Android), NSManagedContext (Objective-C, iOS).

By looking in dictionaries I see that the word means: situation, environment, circumstances etc. However, because I am not a native English speaker I do not understand what I should translate it directly to. For instance, if I were to write a class that either was named SomeClassContext, or a method that had a context parameter, I would not understand when I should name it context because I do not understand it.

I have been searching for context on Stack Overflow, but no question/answers was able to help me.

I would be very happy if someone could provide me with the explanation.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
user772058
  • 2,131
  • 2
  • 13
  • 6
  • 9
    Context is saying: the area within which this object acts. – Blundell May 26 '11 at 21:18
  • 9
    Context is the state of an object or system, at a point in time – Matt May 26 '11 at 22:21
  • Whenever I've seen `context` in a programming situation, it has usually been (outside of a context menu, which is idiomatic) a giant bag of data+functions. It's basically a way to namespace global values. People are trained to think "global = BAD," so they wrap it in a bag in an attempt to get the rule-of-thumb police to look the other way. Kinda like how people wrap liquor in bags hoping nobody knows what's inside. – SO_fix_the_vote_sorting_bug Jul 26 '23 at 22:39

9 Answers9

251

Let's say you go to the dentist to have a tooth pulled out.

When the receptionist asks you for your name, that's information they need in order to begin the appointment. In this example, your name is contextual information. So in the context of visiting the dentist, you need to provide your name to get your tooth pulled.

Now let's say you walk over to the bank.

At the bank, you ask to withdraw $100. The teller needs to establish your identity before giving you money, so you'll probably have to show them a driver's license or swipe your ATM card and enter your PIN number. Either way, what you're providing is context. The teller uses this information to move the transaction forward. They may then ask you which account you'd like to withdraw from. When you answer, "My savings account", that's even more context.

The more context you give, the more knowledge the other party has to help deal with your request. Sometimes context is optional (like typing more and more words into your Google search to get better results) and sometimes it's required (like providing your PIN number at the ATM). Either way, it's information that usually helps to get stuff done.

Now let's say you take your $100 and buy a plane ticket to fly somewhere warm while your mouth heals.

You arrive at a nice sunny destination, but your bag doesn't make it. It's lost somewhere in the airport system. So, you take your "baggage claim ticket" (that sticker with the barcode on it) to the "Lost Baggage office". The first thing the person behind the desk will ask for is that ticket with your baggage number on it. That's an example of some required context.

But then the baggage person asks you for more information about your bag like so they can find it more easily. They ask, "What color is it? What size is it? Does it have wheels? Is it hard or soft? While they don't necessarily need those pieces of information, it helps narrow things down if you provide them. It reduces the problem area. It makes the search much faster. That's optional context.

Here's the interesting part: for a lot of software and APIs, the required context usually ends up as actual parameters in a method signature, and optional context goes somewhere else, like a flexible key-value map that can contain anything (and may be empty) or into thread-local storage where it can be accessed if needed.

The examples above are from real life, but you can easily map them to areas within computer science. For example, HTTP headers contain contextual information. Each header relates to information about the request being made. Or when you're sending along a global transaction ID as part of a two-phase commit process, that transaction ID is context. It helps the transaction manager coordinate the work because it's information about the overall task at hand.

starball
  • 20,030
  • 7
  • 43
  • 238
Brian Kelly
  • 19,067
  • 4
  • 53
  • 55
  • 30
    @Brian:From your post and the other answers given here I think I may start to understand it. An object that carries state information about an event, is a "Context" object? Would that be correct? So a RequestContext object will carry information about a specific request, correct? And when another request come the information attached to the RequestContext-object will change. Is it wrong to say that a context-object is a bit like a DTO (data transfer object)? However a context carries information about different related "things" while DTO's carry information of an object such as a person?Thanks – user772058 May 27 '11 at 09:23
  • 12
    You've nailed it, that's exactly right. A RequestContext will indeed carry information about the request in progress (for example, the locale of the client). Contexts are similar to DTO/VO but are usually not as strongly-typed. But you've got the concept alright. – Brian Kelly May 27 '11 at 13:28
  • 1
    @Brian: Thank you, very good explanation. I think I understand the concept of naming classes end with Context and passing them e.g. in methods, however sometimes you also get a pointer to a context such as currentGraphicContext in iOS, and you invoke methods/selectors on the context, so now the context is not only a state "transfer" object but also an object that you send messages to. I am very sorry that I can't explain it properly but can the context also change things? In Android you extends a Context(Activity, Service etc), is it to access information in the Android OS? – user772058 May 27 '11 at 14:53
  • Typically, no, a context object wouldn't change things itself. It simply stores state and offers getters and setters. However your code may choose to pull data from a context object and do things with it. I'm sure there are some exceptions to that, but in general that's the convention. – Brian Kelly May 27 '11 at 15:08
  • @Brian: Okey, thanks for being patient, I am sorry. I will accept your answer by the evening. I just need to think about what have being said so that I don't have anymore questions. – user772058 May 27 '11 at 16:37
  • 8
    @Brian: One more question was brought to mind, when talking about context-menus, the meaning of context as I learned from this answer does not make sense in my head. As I understand now context is (short) for carry state about something. So, what does it mean when using the word "context" in this way? – user772058 May 27 '11 at 18:01
  • 13
    Good question. The meaning of "context" within "context menu" is, "the stuff you'll see on the menu is dependent on where you click, when you clicked and what else is happening in your application". **Those pieces of information (where/when/what you clicked) represent the context** and would be sent to the GUI code so that it can decide what things to offer on the menu. – Brian Kelly May 27 '11 at 18:12
  • @Brian: Again, thank you very much. I got one more question and I wont bother you anymore. [link](http://developer.android.com/reference/android/content/Context.html) is the superclass of Activity, Service and others. So if I have two different Activities in the same application, wouldn't the context of these be the same? ...TOO long continue next comment.. – user772058 May 27 '11 at 19:15
  • @Brian: They have the same access to the resources haven't they? I mean of would a context menu understand that it should display two different menus? And I write code in a Activity, which inherit from Context (abstract class), is that just for convenience? If the Activity did not inherit the context, every Activity would have e.g. a instance variable which was a reference to the context? – user772058 May 27 '11 at 19:16
  • I'm not an Android programmer at all, so I really won't be able to answer this with any confidence. What you're getting into now is very Android-specific and really warrants a separate question. This might help though - it's another stack overflow answer which sounds related: http://stackoverflow.com/questions/2870678/please-explain-me-context-class-in-android – Brian Kelly May 27 '11 at 19:37
  • 3
    So, parameters of the method are context. Am I wrong? – Can Aydoğan Oct 10 '13 at 20:36
  • @BrianKelly Programming context nicely represented through real world examples . Context will hold all required information for processing request – Rubin Porwal Sep 08 '15 at 06:29
  • "...while your mouth heals." That gave me something akin to what I believe PTSD to be... – SO_fix_the_vote_sorting_bug Jul 26 '23 at 22:29
21

This is 2015 - may years after this thread began.

Nonetheless, I am posting this message to help anyone out there like me that is Struggled to understand "Context"

By no means do I claim to have used Context in Java programs - so its entirely up to you to write Context out in hard coding So here goes :-

"Conceptually context" is the same "as tell me more" When a client makes a request to server - in order to carry out the request the server says "give me some more info so that i can help you". Thus, alongwith the request, the client provides a bundle of details. The server picks and chooses from the bundle all pieces of info required to serve the request. This bundle is what is called "Context"

E.g.

Patient goes to doc and says treat_me ( "I have a headache" ) Doc office gives the patient a form to fill. Patient fills form. The form is used by the doctor to carry out the "treat_me" request.

Here is how the request now looks :

treat_me ( "i have a headache", filled_form_num_23321 ) 

Here is how filled_form_num_23321 looks :

Q.What lead to the condition ? A. 10 pegs of neat Scotch last nite
Q.Patient name ? A. Joe Bigdrinker
Q.Age ? 98

In this transaction filled_form_num_23321 is the "context".

Hope this helps in clarifying the concept of "Context".

Ram
  • 3,092
  • 10
  • 40
  • 56
Ram
  • 211
  • 2
  • 2
18

Context can be seen as a bucket to pass information around. It is typically used to pass things not necessarily tied directly to a method call, but could still be pertinent. A layperson way of describing it might be "stuff you may care about".

For e.g. if you were writing a service to update a value in a db, you'd probably pass in the record id, and the new value.

If you want generic interfaces, you may also define a context to pass, such that the service can perform arbitrary business logic. So you may include a user authentication, the user's session state, etc... in the context, as the service may perform additional logic dependent on these values.

Taylor
  • 3,942
  • 2
  • 20
  • 33
  • 7
    Another useful way to think about it is "information about what is happening". Or more academically, it's "meta information". That's a pretty academic phrase, but it's accurate. In this context. – Brian Kelly May 26 '11 at 21:27
  • 5
    its basically the state at a point in time, no more complex than that – Matt May 26 '11 at 21:57
9

i always think of context as a particular state relevant to the object or construct i am working with.

For example, when you are using drawRect in a view (where all drawing must be done for a view) you must always get the currentGraphicsContext into which you will issue your core graphics statements. This context contains things like bounds of the view, the stroke colour, the stroke thickness for drawing a line, the fill color for filling a closed Path etc. this context (like most others) is just the current state at this point in time. so think of the graphics context in this case as just a set of state such as

stroke thickenss is 1.5 pixels fill color is black bounds of view is (155, 200) stroke color is Red

Its basically the state at the current point in time ...

Matt
  • 4,253
  • 1
  • 27
  • 29
7

Context refers to the execution context, which is the symbols reachable from a given point in the code, and the value of those symbols in that particular execution.

Context is an important concept because:

  1. Executable units (functions, procedures, instructions) may produce different results or behave differently under different contexts.
  2. The larger or more complex the context, the more difficult to understand what a piece of code does (that's why global variables are shunned upon).

You do not have to write context classes or pass context parameters. Any parameter passed to a function/method becomes part of the execution context when it is invoked.

Even though you're not an English speaker, I recommend you go through a copy of Code Complete for a gentle yet thorough introduction to concepts like context, modularity, coupling, cohesion, and so forth.

Apalala
  • 9,017
  • 3
  • 30
  • 48
6

To give a practical example. Lets say you have a certain webpage to fetch/render some information based on the user (thats logged on) and language of the browser. The logic of fetching the information is independent from the user and the language. Your page will receive a user and a language ... for the logic it doesnt matter if it is me or you or english or spanish.

Some pseudo code:

class FooPage
{
    void handleRequest(RequestContext context)
    {
        User user = context.getUser();
        Locale locale = context.getLocale();

        … do some logic based on the context
    }
}

Its not that difficult, but it takes some time to understand the concept

lukin
  • 471
  • 1
  • 4
  • 12
4

Context in your case is the environment where your application is running.

It provides information / services / abilities your application will need in order to run properly.

HTH

user6656519
  • 101
  • 3
1

3 yrs later so maybe a little late, but, maybe this thread would help you. It illustrates that the word "context" has a technical meaning in programming (not just a plain English meaning).

What programming languages are context-free?

Not sure if you can use it as an example and pull some information out of it or not. I too would love to hear a language agnostic explanation of the technical programming term "context"

Edit : Or it at least shows that the term "context" can be applied in a technical, programming context (no punn intended). Possibly in more than one concrete application of the term.

Community
  • 1
  • 1
Jake
  • 189
  • 2
  • 9
0

All too often the author assumes the reader has a detailed understanding of the context the word "context" is being use in.

How do define context in the following sentence "The ? runtime creates a context in which the possible values for injection can be stored. This context can be modified, e.g. the application and the framework can add elements to the context.

It would seem the author is using context to mean some kind of container, perhaps a heap, that holds the context of something. It has become buzz word that is taking on many meaning and confusing things. Is it the elements that are the context and are being stored in a context. To reduce the confusion of the context that the word context is being used it could be said that "the runtime creates a container to store the context in the form of elements." Better yet "the runtime creates a container to store the state in the form of elements and this container with it's state is called the CONTEXT."

john
  • 1