Domain-Specific Languages (DSLs)

Geschätzte Lektüre: 4 Minuten 339 Ansichten

Die Entwicklung domänenspezifischer Sprachen innerhalb von Programmiersprachen ermöglicht expressivere und problemorientierte Code-Strukturen:

// Fluent Interface für SQL-ähnliche Abfragen
class QueryBuilder {
    constructor(data) {
        this.data = data;
        this.filters = [];
        this.sortBy = null;
        this.limitCount = null;
    }
    
    where(predicate) {
        this.filters.push(predicate);
        return this;
    }
    
    orderBy(field, direction = 'asc') {
        this.sortBy = {field, direction};
        return this;
    }
    
    limit(count) {
        this.limitCount = count;
        return this;
    }
    
    execute() {
        let result = [...this.data];
        
        // Filter anwenden
        this.filters.forEach(filter => {
            result = result.filter(filter);
        });
        
        // Sortierung
        if (this.sortBy) {
            result.sort((a, b) => {
                const aVal = a[this.sortBy.field];
                const bVal = b[this.sortBy.field];
                const comparison = aVal < bVal ? -1 : aVal > bVal ? 1 : 0;
                return this.sortBy.direction === 'desc' ? -comparison : comparison;
            });
        }
        
        // Limit
        if (this.limitCount) {
            result = result.slice(0, this.limitCount);
        }
        
        return result;
    }
}

// Verwendung der DSL
const users = [
    {name: "Alice", age: 30, department: "Engineering"},
    {name: "Bob", age: 25, department: "Marketing"},
    {name: "Charlie", age: 35, department: "Engineering"},
    {name: "Diana", age: 28, department: "Sales"}
];

const query = new QueryBuilder(users)
    .where(user => user.age > 26)
    .where(user => user.department === "Engineering")
    .orderBy('name')
    .limit(5)
    .execute();

console.log(query); // [{name: "Alice", age: 30, department: "Engineering"}, ...]

// Template-basierte DSL für HTML-Generierung
const html = (strings, ...values) => {
    return strings.reduce((result, string, i) => {
        const value = values[i] ? values[i] : '';
        return result + string + value;
    }, '');
};

const createElement = (tag, attributes = {}, content = '') => {
    const attrs = Object.entries(attributes)
        .map(([key, value]) => `${key}="${value}"`)
        .join(' ');
    
    return `<${tag}${attrs ? ' ' + attrs : ''}>${content}</${tag}>`;
};

// Verwendung
const userCard = (user) => html`
    <div class="user-card">
        ${createElement('h2', {}, user.name)}
        ${createElement('p', {}, `Age: ${user.age}`)}
        ${createElement('span', {class: 'department'}, user.department)}
    </div>
`;
Dieses Dokument teilen

Domain-Specific Languages (DSLs)

Oder Link kopieren

INHALT

Abonnieren

×
Cancel