SlideShare a Scribd company logo
©2007Martinv.Löwis
Context-Oriented Programming:
Beyond Layers
Martin v. Löwis
Marcus Denker
Oscar Nierstrasz
Context-oriented Programming: Beyond Layers
©2007Martinv.Löwis
Agenda
• Context-dependent Behavior
• Method Layers (PyContext example)
• Implicit Layer Activation
• Case Studies
• Context Variables
• Implementation Notes
2
Context-oriented Programming: Beyond Layers
©2007Martinv.Löwis
Context Dependencies
• Programs need to be aware of the context in which they
operate
– what is the state of the environment
– what user is accessing the system
– what mode is the program to be executed in
• Example: current user
– different roles may cause completely different code to be executed
(e.g. administrator may be offered different facilities)
• can be modeled through method layers
– different users acting in the same role access different data
• modeling through method layers is not adequate
• Example: dependency of program output on output device
– In OO system, rendering algorithm spreads over methods of
different classes
3
©2007Martinv.Löwis
Layers
Context-oriented Programming: Beyond Layers
©2007Martinv.Löwis
Method Layers
• addition of a few concepts to object-oriented programming
• layer: group of classes and methods to be used together in
dynamic scope of execution
• layered class: collection of partial definitions of a class, for
different layers
– layered methods: definitions of methods for specific layers
– layered slots: definition of instance attributes for specific layers
• (explicit) layer activation: specification of code block that
runs in the context of a layer
– inside the block, each sent message selects the method defined for
that layer
– nested activation: need to consider multiple layers in sequence
5
Context-oriented Programming: Beyond Layers
©2007Martinv.Löwis
Example: User-Agent Header
• Web browsers sent User-Agent header to indicate client
software (e.g. MSIE, Firefox, Safari, etc.)
– "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)"
• Web servers sometimes have different behavior depending
on User-Agent header
• Problem: automated web client might need to claim to
operate as a specific user agent
6
Client
HTTP Library
HTTP ServerHTTP
Request
User-Agent
Context-oriented Programming: Beyond Layers
©2007Martinv.Löwis
Example: User-Agent Header (2)
• Assumption: client consists of multiple modules, each using
different software layers to access underlying HTTP libraries
– explicitly specifying User-Agent to the library is not possible
• Assumption: client is multi-threaded; different threads may
need to operate in different contexts
– setting User-Agent as a global variable is not possible
• HTTP libraries in Python:
– httplib: direct access to protocol
– urllib: unifying library for http, ftp, ...
7
Context-oriented Programming: Beyond Layers
©2007Martinv.Löwis
PyContext: Using Method Layers
• with statement: automatic enter/leave semantics
from useragent import HTTPUserAgent
with HTTPUserAgent("WebCOP"):
print "Using useragent layer"
get1()
get2()
• Importing useragent module automatically defines the layer
and the layered methods
• Disabling layers
from layers import Disabled
with Disabled(Layer):
code
8
Context-oriented Programming: Beyond Layers
©2007Martinv.Löwis
Defining Layers
• Inherit from class Layer
– Class can have arbitrary methods, instance variables, etc
class HTTPUserAgent(layers.Layer):
def __init__(self, agent):
self.agent = agent
9
Context-oriented Programming: Beyond Layers
©2007Martinv.Löwis
Defining Layered Methods
• Inherit a class (with arbitrary name) from both the layer and
the class to augment
• Define methods with the same name as the original methods
– Each method has automatic second parameter "context" (after self,
before explicit method parameters)
• Decorate each method with either before, after, or instead
• Context: Object indicating the layer activation
– .layer: reference to the layer object
– .result: result of the original method (for after-methods)
– .proceed: callable object denoting the continuation to the original
method (or the next layer)
10
Context-oriented Programming: Beyond Layers
©2007Martinv.Löwis
class HTTPConnection(HTTPUserAgent, httplib.HTTPConnection):
# Always add a User-Agent header
@before
def endheaders(self, context):
with layers.Disabled(HTTPUserAgent):
self.putheader("User-Agent", context.layer.agent)
# suppress other User-Agent headers added
@instead
def putheader(self, context, header, value):
if header.lower() == 'user-agent':
return
return context.proceed(header, value)
11
©2007Martinv.Löwis
Implicit Activation
Context-oriented Programming: Beyond Layers
©2007Martinv.Löwis
Implicit Activation
• Problem: explicit activation still needs to identify point in
code where context might change or where context will be
relevant
• Objective: allow addition of layers which get activated
"automatically"
– specifically, when a condition on the environment changes
• Design issues:
– how can the system tell whether a condition becomes true?
• each layer implements an active method
– when should the active method be evaluated?
• each time a layered method is executed whose meaning depends on
whether the layer is active or not
13
©2007Martinv.Löwis
Case Studies
Context-oriented Programming: Beyond Layers
©2007Martinv.Löwis
Objective
• We tried to evaluate what aspects of context are common in
application programs today
• Issue: how can we find code that depends on context?
– Starting point: assume caller and callee are designed to run within
the same context
– Starting point: look for traditional examples of context
• Selected case studies: large Python applications/libraries
– Django: web application framework
– Roundup: bug tracker
– SCons: automated build tool
15
Context-oriented Programming: Beyond Layers
©2007Martinv.Löwis
Results
• Web applications (Django, Roundup) need to support
concept of "current" request, including authenticated user,
session data, target URL, etc.
• SCons keeps track of context in "environment": information
about the current build goal
• These things were often referred to as "context", or showed
up as pass-through parameters in methods
– Searching for "context" revealed further context-dependent code
fragments
– Searching for pass-through parameters not easily possible with pure
text searching; subject for further study
• Context information often not used to select different pieces
of code, but merely as lookup keys in associative arrays
16
©2007Martinv.Löwis
Dynamic Variables
Context-oriented Programming: Beyond Layers
©2007Martinv.Löwis
Motivation
• case study results lead to identification of additional concept
for context-oriented programming: Dynamic Variables
• in order to avoid pass-through parameters, a variable holding
context should be set in a caller, and then read in a nested
callee
– similar to dynamic variables in functional languages
– requires careful usage, to avoid old problems with dynamic variables
(unintentional access due to naming collisions)
• require explicit read and write operations
18
Context-oriented Programming: Beyond Layers
©2007Martinv.Löwis
Dynamic Variables in PyContext
• Example: current HTTP session
1. Declare dynamic variable
_session = Variable()
2. Obtain current variable (e.g. through helper function)
def current_session():
return _session.get()
3. Setup variable from dynamically-read context
def process_request(request):
session = lookup_session(request)
with _session.set(session):
dispatch_request(request)
19
Context-oriented Programming: Beyond Layers
©2007Martinv.Löwis
Implementation Notes
• Method layers:
– Dynamically replace methods with wrappers
• Dynamic variables:
1. perform stack walk: O(stack-depth)
2. use thread-local storage: O(1)
20
Context-oriented Programming: Beyond Layers
©2007Martinv.Löwis
Summary
• current applications (in particular webapps) show high
degree of context-awareness
• context-dependency is not made explicit in the code
• layers are a first step to making context explicit
• rehabilitation of dynamic variables necessary to support
common cases of context
21

More Related Content

PDF
Reflection
PPTX
SNAPL Network Verification
PPTX
Architectural patterns part 4
PPTX
Architectural patterns part 3
PPTX
Mule mel 2
PPT
Active Object
PPTX
Mule mel 1
PDF
Demo: Reflectivity
Reflection
SNAPL Network Verification
Architectural patterns part 4
Architectural patterns part 3
Mule mel 2
Active Object
Mule mel 1
Demo: Reflectivity

What's hot (20)

PPTX
Architectural Patterns - Interactive and Event Handling Patterns
PPTX
Project Reactor By Example
PPTX
Vert.x Event Driven Non Blocking Reactive Toolkit
PDF
ITFT_Inter process communication
PDF
Active Object Design Pattern
PPTX
Multi-Process JavaScript Architectures
PPTX
Reactive Programming In Java Using: Project Reactor
PDF
Advanced Application Architecture Symfony Live Berlin 2018
ODP
Polling Techniques, Ajax, protocol Switching from Http to Websocket standard ...
PPTX
Design patterns
PDF
Introduction to reactive programming
PPTX
Build Libraries That People Love To use
PDF
Reflectivity Demo
PPTX
Reactive programming
PPTX
Reactive programming with rx java
PPT
Vulnerability Chaining; it’s all connected
PDF
Reactive programming and RxJS
PDF
Concurrency
PPTX
Reactive programming intro
PPTX
ProMan(Project Management in python language using KIVY platform)
Architectural Patterns - Interactive and Event Handling Patterns
Project Reactor By Example
Vert.x Event Driven Non Blocking Reactive Toolkit
ITFT_Inter process communication
Active Object Design Pattern
Multi-Process JavaScript Architectures
Reactive Programming In Java Using: Project Reactor
Advanced Application Architecture Symfony Live Berlin 2018
Polling Techniques, Ajax, protocol Switching from Http to Websocket standard ...
Design patterns
Introduction to reactive programming
Build Libraries That People Love To use
Reflectivity Demo
Reactive programming
Reactive programming with rx java
Vulnerability Chaining; it’s all connected
Reactive programming and RxJS
Concurrency
Reactive programming intro
ProMan(Project Management in python language using KIVY platform)
Ad

Viewers also liked (12)

PDF
Aspect-oriented programming with AspectJ (as part of the the PTT lecture)
PDF
SeaJUG Dec 2001: Aspect-Oriented Programming with AspectJ
PPT
Aspect oriented architecture
PPTX
Produce Cleaner Code with Aspect-Oriented Programming
PPTX
Aspect Oriented Programming
ODP
Aspect-Oriented Programming
PDF
Architecture Description Languages
PPTX
Aspect Oriented Programming
PPTX
Introduction to Aspect Oriented Programming (DDD South West 4.0)
PPTX
Introduction to Aspect Oriented Programming
PDF
Software Architecture: Architecture Description Languages
PPT
Aspect Oriented Programming
Aspect-oriented programming with AspectJ (as part of the the PTT lecture)
SeaJUG Dec 2001: Aspect-Oriented Programming with AspectJ
Aspect oriented architecture
Produce Cleaner Code with Aspect-Oriented Programming
Aspect Oriented Programming
Aspect-Oriented Programming
Architecture Description Languages
Aspect Oriented Programming
Introduction to Aspect Oriented Programming (DDD South West 4.0)
Introduction to Aspect Oriented Programming
Software Architecture: Architecture Description Languages
Aspect Oriented Programming
Ad

Similar to Context-Oriented Programming: Beyond Layers (20)

PDF
Rapid Web Development with Python for Absolute Beginners
PDF
Architecture Patterns with Python 1st Edition Harry Percival
PDF
Instant download Architecture Patterns with Python 1st Edition Harry Percival...
PPTX
Futureproofing REST APIs
PDF
Enterprise-Ready FastAPI: Beyond the Basics
ZIP
Pylons - An Overview: Rapid MVC Web Development with WSGI
PDF
Architecture Patterns with Python 1st Edition Harry Percival
PDF
Better Laziness Through Hypermedia -- Designing a Hypermedia Client
PDF
Web application architecture
PDF
Python and the Web
PPTX
Software Programming with Python II.pptx
PPTX
Web development with Python
PPTX
DEMO On PYTHON WEB Development.pptx
PDF
Python and Zope: An introduction (May 2004)
PDF
Python Load Testing - Pygotham 2012
PPTX
Web Dev 21-01-2024.pptx
PPTX
Rest APIs Training
DOCX
Akash rajguru project report sem v
PPTX
2018 12-kube con-ballerinacon
PDF
API Design & Security in django
Rapid Web Development with Python for Absolute Beginners
Architecture Patterns with Python 1st Edition Harry Percival
Instant download Architecture Patterns with Python 1st Edition Harry Percival...
Futureproofing REST APIs
Enterprise-Ready FastAPI: Beyond the Basics
Pylons - An Overview: Rapid MVC Web Development with WSGI
Architecture Patterns with Python 1st Edition Harry Percival
Better Laziness Through Hypermedia -- Designing a Hypermedia Client
Web application architecture
Python and the Web
Software Programming with Python II.pptx
Web development with Python
DEMO On PYTHON WEB Development.pptx
Python and Zope: An introduction (May 2004)
Python Load Testing - Pygotham 2012
Web Dev 21-01-2024.pptx
Rest APIs Training
Akash rajguru project report sem v
2018 12-kube con-ballerinacon
API Design & Security in django

More from ESUG (20)

PDF
ShowUs: Pharo Stream Deck (ESUG 2025, Gdansk)
PDF
Micromaid: A simple Mermaid-like chart generator for Pharo
PDF
Directing Generative AI for Pharo Documentation
PDF
Even Lighter Than Lightweiht: Augmenting Type Inference with Primitive Heuris...
PDF
Composing and Performing Electronic Music on-the-Fly with Pharo and Coypu
PDF
Gamifying Agent-Based Models in Cormas: Towards the Playable Architecture for...
PDF
Analysing Python Machine Learning Notebooks with Moose
PDF
FASTTypeScript metamodel generation using FAST traits and TreeSitter project
PDF
Migrating Katalon Studio Tests to Playwright with Model Driven Engineering
PDF
Package-Aware Approach for Repository-Level Code Completion in Pharo
PDF
Evaluating Benchmark Quality: a Mutation-Testing- Based Methodology
PDF
An Analysis of Inline Method Refactoring
PDF
Identification of unnecessary object allocations using static escape analysis
PDF
Control flow-sensitive optimizations In the Druid Meta-Compiler
PDF
Clean Blocks (IWST 2025, Gdansk, Poland)
PDF
Encoding for Objects Matters (IWST 2025)
PDF
Challenges of Transpiling Smalltalk to JavaScript
PDF
Immersive experiences: what Pharo users do!
PDF
ChatPharo: an Open Architecture for Understanding How to Talk Live to LLMs
PDF
Cavrois - an Organic Window Management (ESUG 2025)
ShowUs: Pharo Stream Deck (ESUG 2025, Gdansk)
Micromaid: A simple Mermaid-like chart generator for Pharo
Directing Generative AI for Pharo Documentation
Even Lighter Than Lightweiht: Augmenting Type Inference with Primitive Heuris...
Composing and Performing Electronic Music on-the-Fly with Pharo and Coypu
Gamifying Agent-Based Models in Cormas: Towards the Playable Architecture for...
Analysing Python Machine Learning Notebooks with Moose
FASTTypeScript metamodel generation using FAST traits and TreeSitter project
Migrating Katalon Studio Tests to Playwright with Model Driven Engineering
Package-Aware Approach for Repository-Level Code Completion in Pharo
Evaluating Benchmark Quality: a Mutation-Testing- Based Methodology
An Analysis of Inline Method Refactoring
Identification of unnecessary object allocations using static escape analysis
Control flow-sensitive optimizations In the Druid Meta-Compiler
Clean Blocks (IWST 2025, Gdansk, Poland)
Encoding for Objects Matters (IWST 2025)
Challenges of Transpiling Smalltalk to JavaScript
Immersive experiences: what Pharo users do!
ChatPharo: an Open Architecture for Understanding How to Talk Live to LLMs
Cavrois - an Organic Window Management (ESUG 2025)

Recently uploaded (20)

PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
sap open course for s4hana steps from ECC to s4
PPTX
MYSQL Presentation for SQL database connectivity
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
A Presentation on Artificial Intelligence
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
Cloud computing and distributed systems.
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
Spectroscopy.pptx food analysis technology
PDF
Empathic Computing: Creating Shared Understanding
PPTX
Machine Learning_overview_presentation.pptx
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
sap open course for s4hana steps from ECC to s4
MYSQL Presentation for SQL database connectivity
“AI and Expert System Decision Support & Business Intelligence Systems”
A Presentation on Artificial Intelligence
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Cloud computing and distributed systems.
Chapter 3 Spatial Domain Image Processing.pdf
Dropbox Q2 2025 Financial Results & Investor Presentation
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Spectroscopy.pptx food analysis technology
Empathic Computing: Creating Shared Understanding
Machine Learning_overview_presentation.pptx
Network Security Unit 5.pdf for BCA BBA.
MIND Revenue Release Quarter 2 2025 Press Release
Mobile App Security Testing_ A Comprehensive Guide.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
20250228 LYD VKU AI Blended-Learning.pptx
Diabetes mellitus diagnosis method based random forest with bat algorithm

Context-Oriented Programming: Beyond Layers

  • 2. Context-oriented Programming: Beyond Layers ©2007Martinv.Löwis Agenda • Context-dependent Behavior • Method Layers (PyContext example) • Implicit Layer Activation • Case Studies • Context Variables • Implementation Notes 2
  • 3. Context-oriented Programming: Beyond Layers ©2007Martinv.Löwis Context Dependencies • Programs need to be aware of the context in which they operate – what is the state of the environment – what user is accessing the system – what mode is the program to be executed in • Example: current user – different roles may cause completely different code to be executed (e.g. administrator may be offered different facilities) • can be modeled through method layers – different users acting in the same role access different data • modeling through method layers is not adequate • Example: dependency of program output on output device – In OO system, rendering algorithm spreads over methods of different classes 3
  • 5. Context-oriented Programming: Beyond Layers ©2007Martinv.Löwis Method Layers • addition of a few concepts to object-oriented programming • layer: group of classes and methods to be used together in dynamic scope of execution • layered class: collection of partial definitions of a class, for different layers – layered methods: definitions of methods for specific layers – layered slots: definition of instance attributes for specific layers • (explicit) layer activation: specification of code block that runs in the context of a layer – inside the block, each sent message selects the method defined for that layer – nested activation: need to consider multiple layers in sequence 5
  • 6. Context-oriented Programming: Beyond Layers ©2007Martinv.Löwis Example: User-Agent Header • Web browsers sent User-Agent header to indicate client software (e.g. MSIE, Firefox, Safari, etc.) – "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)" • Web servers sometimes have different behavior depending on User-Agent header • Problem: automated web client might need to claim to operate as a specific user agent 6 Client HTTP Library HTTP ServerHTTP Request User-Agent
  • 7. Context-oriented Programming: Beyond Layers ©2007Martinv.Löwis Example: User-Agent Header (2) • Assumption: client consists of multiple modules, each using different software layers to access underlying HTTP libraries – explicitly specifying User-Agent to the library is not possible • Assumption: client is multi-threaded; different threads may need to operate in different contexts – setting User-Agent as a global variable is not possible • HTTP libraries in Python: – httplib: direct access to protocol – urllib: unifying library for http, ftp, ... 7
  • 8. Context-oriented Programming: Beyond Layers ©2007Martinv.Löwis PyContext: Using Method Layers • with statement: automatic enter/leave semantics from useragent import HTTPUserAgent with HTTPUserAgent("WebCOP"): print "Using useragent layer" get1() get2() • Importing useragent module automatically defines the layer and the layered methods • Disabling layers from layers import Disabled with Disabled(Layer): code 8
  • 9. Context-oriented Programming: Beyond Layers ©2007Martinv.Löwis Defining Layers • Inherit from class Layer – Class can have arbitrary methods, instance variables, etc class HTTPUserAgent(layers.Layer): def __init__(self, agent): self.agent = agent 9
  • 10. Context-oriented Programming: Beyond Layers ©2007Martinv.Löwis Defining Layered Methods • Inherit a class (with arbitrary name) from both the layer and the class to augment • Define methods with the same name as the original methods – Each method has automatic second parameter "context" (after self, before explicit method parameters) • Decorate each method with either before, after, or instead • Context: Object indicating the layer activation – .layer: reference to the layer object – .result: result of the original method (for after-methods) – .proceed: callable object denoting the continuation to the original method (or the next layer) 10
  • 11. Context-oriented Programming: Beyond Layers ©2007Martinv.Löwis class HTTPConnection(HTTPUserAgent, httplib.HTTPConnection): # Always add a User-Agent header @before def endheaders(self, context): with layers.Disabled(HTTPUserAgent): self.putheader("User-Agent", context.layer.agent) # suppress other User-Agent headers added @instead def putheader(self, context, header, value): if header.lower() == 'user-agent': return return context.proceed(header, value) 11
  • 13. Context-oriented Programming: Beyond Layers ©2007Martinv.Löwis Implicit Activation • Problem: explicit activation still needs to identify point in code where context might change or where context will be relevant • Objective: allow addition of layers which get activated "automatically" – specifically, when a condition on the environment changes • Design issues: – how can the system tell whether a condition becomes true? • each layer implements an active method – when should the active method be evaluated? • each time a layered method is executed whose meaning depends on whether the layer is active or not 13
  • 15. Context-oriented Programming: Beyond Layers ©2007Martinv.Löwis Objective • We tried to evaluate what aspects of context are common in application programs today • Issue: how can we find code that depends on context? – Starting point: assume caller and callee are designed to run within the same context – Starting point: look for traditional examples of context • Selected case studies: large Python applications/libraries – Django: web application framework – Roundup: bug tracker – SCons: automated build tool 15
  • 16. Context-oriented Programming: Beyond Layers ©2007Martinv.Löwis Results • Web applications (Django, Roundup) need to support concept of "current" request, including authenticated user, session data, target URL, etc. • SCons keeps track of context in "environment": information about the current build goal • These things were often referred to as "context", or showed up as pass-through parameters in methods – Searching for "context" revealed further context-dependent code fragments – Searching for pass-through parameters not easily possible with pure text searching; subject for further study • Context information often not used to select different pieces of code, but merely as lookup keys in associative arrays 16
  • 18. Context-oriented Programming: Beyond Layers ©2007Martinv.Löwis Motivation • case study results lead to identification of additional concept for context-oriented programming: Dynamic Variables • in order to avoid pass-through parameters, a variable holding context should be set in a caller, and then read in a nested callee – similar to dynamic variables in functional languages – requires careful usage, to avoid old problems with dynamic variables (unintentional access due to naming collisions) • require explicit read and write operations 18
  • 19. Context-oriented Programming: Beyond Layers ©2007Martinv.Löwis Dynamic Variables in PyContext • Example: current HTTP session 1. Declare dynamic variable _session = Variable() 2. Obtain current variable (e.g. through helper function) def current_session(): return _session.get() 3. Setup variable from dynamically-read context def process_request(request): session = lookup_session(request) with _session.set(session): dispatch_request(request) 19
  • 20. Context-oriented Programming: Beyond Layers ©2007Martinv.Löwis Implementation Notes • Method layers: – Dynamically replace methods with wrappers • Dynamic variables: 1. perform stack walk: O(stack-depth) 2. use thread-local storage: O(1) 20
  • 21. Context-oriented Programming: Beyond Layers ©2007Martinv.Löwis Summary • current applications (in particular webapps) show high degree of context-awareness • context-dependency is not made explicit in the code • layers are a first step to making context explicit • rehabilitation of dynamic variables necessary to support common cases of context 21