SlideShare ist ein Scribd-Unternehmen logo
1 von 38
Mårten Rånge
@marten_range
Model driven MetaProgramming
Using Visual Studio & T4
Let’s talk about code
DNRY
Do Not Repeat Yourself
Repeating myself
[Serializable]
public class AnException : Exception
{
public AnException ();
public AnException (string message);
public AnException (string message, Exception exc);
protected AnException (
SerializationInfo info, StreamingContext context);
[SecurityPermission(
SecurityAction.Demand, SerializationFormatter = true)]
public override void GetObjectData (
SerializationInfo info, StreamingContext context)
}
Repeating myself
AnException

Exception
Repeating myself
[Serializable]
public class AnException : Exception
{
public AnException ();
public AnException (string message);
public AnException (string message, Exception exc);
protected AnException (
SerializationInfo info, StreamingContext context);
[SecurityPermission(
SecurityAction.Demand, SerializationFormatter = true)]
public override void GetObjectData (
SerializationInfo info, StreamingContext context)
}
Repeating myself
public class MyViewModel : INotifyPropertyChanged
{
public int MyProperty
{
get { return m_myProperty; }
set
{
m_myProperty = value
OnRaisePropertyChanged ("MyProperty")
}
}
void OnRaisePropertyChanged (string propertyName);
}
Repeating myself
int MyProperty
Repeating myself
public class MyViewModel : INotifyPropertyChanged
{
public int MyProperty
{
get { return m_myProperty; }
set
{
m_myProperty = value
OnRaisePropertyChanged ("MyProperty")
}
}
void OnRaisePropertyChanged (string propertyName);
}
Repeating myself
public static readonly DependencyProperty PreviewWidthProperty =
DependencyProperty.Register (
"PreviewWidth",
typeof (double),
typeof (AccordionPanel),
new FrameworkPropertyMetadata (32.0));

public double PreviewWidth
{
get { return (double)GetValue (PreviewWidthProperty); }
set { if (PreviewWidth != value)
SetValue (PreviewWidthProperty, value); }
}
Repeating myself

double PreviewWidth
Repeating myself
public static readonly DependencyProperty PreviewWidthProperty =
DependencyProperty.Register (
"PreviewWidth",
typeof (double),
typeof (AccordionPanel),
new FrameworkPropertyMetadata (32.0));

public double PreviewWidth
{
get { return (double)GetValue (PreviewWidthProperty); }
set { if (PreviewWidth != value)
SetValue (PreviewWidthProperty, value); }
}
Deliver maximum business value for minimal cost
Code redundancy increase cost
Longer development times
Inconsistent behavior
Costlier maintenance
Stops us from doing the right thing
Tools to reduce redundancy
Loops
Methods
Polymorphism
Generics
Higher-order functions
Sometimes they don’t help
MetaProgramming
MetaProgramming is code that codes
T4 is MetaProgramming
Demo.001
Getting started with T4
T4 – ASP/PHP for code
class X
{
<# for (var iter = 0; iter < 10; ++iter) { #>
public int X<#=iter#> = <#=iter#>;
<# } #>
}
Exceptions revisited
[Serializable]
public class AnException : Exception
{
public AnException ();
public AnException (string message);
public AnException (string message, Exception exc);
protected AnException (
SerializationInfo info, StreamingContext context);
[SecurityPermission(
SecurityAction.Demand, SerializationFormatter = true)]
public override void GetObjectData (
SerializationInfo info, StreamingContext context)
}
Exceptions revisited
Exception sample from
“The CORRECT Way to Code a Custom Exception Class”
bit.ly/10TzZAh
@dseelinger
Exceptions revisited

C# lacks constructor forwarding
A weakness in the language
Demo.002
Generating exception classes
Exceptions revisited

MetaProgramming can combat code redundancy
caused by weaknesses in the language
Autobiographical examples
MC68000 – Self modifying code
C/C++
- Higher order macros
C++ - Partial template specialization
.NET
– System.Reflection.Emit
.NET
– System.Linq.Expressions
T-SQL
– SELECT * FROM SYS.tables

Visual Studio – T4
Benefits of T4
Simple concept
ASP/PHP for code

Easy to debug
The generated code can be debugged just as easy as hand
written code

Flexible
T4 can generate any text artifact
C#
VB
C++

Doesn’t affect deployment
Additional resources
Visual Studio Pro
2008, 2010 or 2012

T4 Addin
http://t4-editor.tangible-engineering.com/

Good T4 Blog
http://www.olegsych.com/
Best practices
The rule of two
Separate model & template
Separate generated & crafted code
partial class X
{
partial void Partial_Y (int q, ref int a);
public int Y (int q)
{
var a = 0;
Partial_Y(q, ref a);
return a;
}
}
Demo.003
Generating Dependency Properties with T4
DependencyProperties (WPF)
Controls requires DependencyProperties
DependencyProperty pattern  Redundant code
Becomes inconsistent
Error prone
Naming conventions
Takes a long time to write
Is mind-numbingly boring to write

T4 can help
T4 – ASP/PHP for code
class X
{
<# for (var iter = 0; iter < 10; ++iter) { #>
public int X<#=iter#> = <#=iter#>;
<# } #>
}
T4 saved me
MetaProgramming for me
Saves time
Improves quality
Puts the fun back into (meta)programming
Mårten Rånge
@marten_range

Weitere ähnliche Inhalte

Was ist angesagt? (11)

Exception Handling
Exception HandlingException Handling
Exception Handling
 
Listen afup 2010
Listen afup 2010Listen afup 2010
Listen afup 2010
 
C++ boot camp part 1/2
C++ boot camp part 1/2C++ boot camp part 1/2
C++ boot camp part 1/2
 
Catch and throw blocks
Catch and throw blocksCatch and throw blocks
Catch and throw blocks
 
Exception handlingpdf
Exception handlingpdfException handlingpdf
Exception handlingpdf
 
C format string vulnerability
C format string vulnerabilityC format string vulnerability
C format string vulnerability
 
TDD in C - Recently Used List Kata
TDD in C - Recently Used List KataTDD in C - Recently Used List Kata
TDD in C - Recently Used List Kata
 
Exception Handling in the C++ Constructor
Exception Handling in the C++ ConstructorException Handling in the C++ Constructor
Exception Handling in the C++ Constructor
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in java
 
Handling Exceptions In C &amp; C++[Part A]
Handling Exceptions In C &amp; C++[Part A]Handling Exceptions In C &amp; C++[Part A]
Handling Exceptions In C &amp; C++[Part A]
 
Format string vunerability
Format string vunerabilityFormat string vunerability
Format string vunerability
 

Ähnlich wie Meta Programming

NNUG Certification Presentation
NNUG Certification PresentationNNUG Certification Presentation
NNUG Certification Presentation
Niall Merrigan
 
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Carol McDonald
 
Spring 3: What's New
Spring 3: What's NewSpring 3: What's New
Spring 3: What's New
Ted Pennings
 

Ähnlich wie Meta Programming (20)

Paradigmas de linguagens de programacao - aula#9
Paradigmas de linguagens de programacao - aula#9Paradigmas de linguagens de programacao - aula#9
Paradigmas de linguagens de programacao - aula#9
 
E:\Plp 2009 2\Plp 9
E:\Plp 2009 2\Plp 9E:\Plp 2009 2\Plp 9
E:\Plp 2009 2\Plp 9
 
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
 
Attributes & .NET components
Attributes & .NET componentsAttributes & .NET components
Attributes & .NET components
 
Static program analysis tools
Static program analysis toolsStatic program analysis tools
Static program analysis tools
 
NNUG Certification Presentation
NNUG Certification PresentationNNUG Certification Presentation
NNUG Certification Presentation
 
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
 
Java day 2016.pptx
Java day 2016.pptxJava day 2016.pptx
Java day 2016.pptx
 
Spring 3: What's New
Spring 3: What's NewSpring 3: What's New
Spring 3: What's New
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Java Performance Tuning
Java Performance TuningJava Performance Tuning
Java Performance Tuning
 
Framework engineering JCO 2011
Framework engineering JCO 2011Framework engineering JCO 2011
Framework engineering JCO 2011
 
Using the Windows 8 Runtime from C++
Using the Windows 8 Runtime from C++Using the Windows 8 Runtime from C++
Using the Windows 8 Runtime from C++
 
Java Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPRECJava Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPREC
 
Java Notes
Java Notes Java Notes
Java Notes
 
Object Oriented Code RE with HexraysCodeXplorer
Object Oriented Code RE with HexraysCodeXplorerObject Oriented Code RE with HexraysCodeXplorer
Object Oriented Code RE with HexraysCodeXplorer
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
Srgoc dotnet
Srgoc dotnetSrgoc dotnet
Srgoc dotnet
 
Jersey Guice AOP
Jersey Guice AOPJersey Guice AOP
Jersey Guice AOP
 
Annotation processor and compiler plugin
Annotation processor and compiler pluginAnnotation processor and compiler plugin
Annotation processor and compiler plugin
 

Mehr von Mårten Rånge

Mehr von Mårten Rånge (10)

Know your FOSS obligations
Know your FOSS obligationsKnow your FOSS obligations
Know your FOSS obligations
 
Ray Marching Explained
Ray Marching ExplainedRay Marching Explained
Ray Marching Explained
 
Better performance through Superscalarity
Better performance through SuperscalarityBetter performance through Superscalarity
Better performance through Superscalarity
 
Property Based Tesing
Property Based TesingProperty Based Tesing
Property Based Tesing
 
Monad - a functional design pattern
Monad - a functional design patternMonad - a functional design pattern
Monad - a functional design pattern
 
Formlets
FormletsFormlets
Formlets
 
Pragmatic metaprogramming
Pragmatic metaprogrammingPragmatic metaprogramming
Pragmatic metaprogramming
 
Concurrency - responsiveness in .NET
Concurrency - responsiveness in .NETConcurrency - responsiveness in .NET
Concurrency - responsiveness in .NET
 
Concurrency scalability
Concurrency scalabilityConcurrency scalability
Concurrency scalability
 
Concurrency
ConcurrencyConcurrency
Concurrency
 

Kürzlich hochgeladen

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Kürzlich hochgeladen (20)

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

Meta Programming