q2K BHP
Black History Portal
THE BHP WIRE —
HIDDEN TRUTHS
What's New!
THE JOURNEY THROUGH TIME

Explore Black History

Explore the people, places, events, achievements, struggles and stories that shaped our journey.

✊🏾

Civil Rights

Movements, leaders, victories and the continuing fight for equality.

⚙️

Black Inventors

Innovation, patents, science, technology and world-changing contributions.

🏆

Sports

Pioneers, champions, Negro Leagues, records, activism and excellence.

♟️

People

Meet the people whose lives, choices and achievements shaped the journey.

📍

Places

Black towns, communities, institutions and places where history happened.

📜

Events

Moments that changed communities, movements, institutions and the nation.

Enter a person, place, event, or topic.
MY'STORY

The MOVE Fire

This is a personal recollection on the Move fire on May 13, 1985 Philadelphia police fired thousands of rounds at the MOVE house, city officials approved dropping an explosive device on the roof, the resulting fire was allowed to burn, 11 people—including five children—died, and 61 homes were destroyed. Philadelphia City Council later called it a “brutal attack carried out by the City of Philadelphia on its own citizens” and acknowledged that no individual faced criminal consequences for the bombing. One timeline correction worth preserving for the BHP record: the major previous MOVE-police confrontation was August 8, 1978, about seven years before the bombing, not a year or two earlier. Officer James Ramp was killed, other police and firefighters were wounded, nine MOVE members were later convicted, and television cameras recorded police beating Delbert Africa during his arrest. The 1985 MOVE Commission later specifically criticized city planners for failing to adequately use lessons from that 1978 confrontation. And that actually strengthens the point you’re making: 1985 did not happen without precedent or institutional memory. There had already been a deadly confrontation with MOVE, years of conflict, negotiations and police involvement before Osage Avenue.

MORE →
BLACK FACTS
The Truths They Never Taught You...

Ruler of the Mali Empire in the 14th century

Mansa Musa was the ruler of the Mali Empire in West Africa. Details recorded here should be sourced; unknown information is left blank.

MORE →
BHP gathered finds from its connected research sources. Showing the 4 strongest Black History matches.
← BACK TO RESULTS
Wikipedia

Extension method

In object-oriented computer programming, an extension method is a method added to an object after the original object was compiled. The modified object is often a class, a prototype, or a type. Extension methods are features of some object-oriented programming languages. There is no syntactic difference between calling an extension method and calling a method declared in the type definition.[1]

Not all languages implement extension methods in an equally safe manner, however. For instance, languages such as C#, Java (via Manifold, Lombok, or Fluent), and Kotlin don't alter the extended class in any way, because doing so may break class hierarchies and interfere with virtual method dispatching. Instead, these languages strictly implement extension methods statically and use static dispatching to invoke them.

Support in programming languages

[edit]

Extension methods are features of numerous languages including C#, Java via Manifold or Lombok or Fluent, Gosu, JavaScript, Oxygene, Ruby, Smalltalk, Kotlin, Dart, Visual Basic.NET, and Xojo. In dynamic languages like Python, the concept of an extension method is unnecessary because classes (excluding built-in classes) can be extended without any special syntax (an approach known as "monkey-patching", employed in libraries such as gevent).

In VB.NET and Oxygene, they are recognized by the presence of the "extension" keyword or attribute. In Xojo, the "Extends" keyword is used with global methods.

In C#, they are implemented as static methods in static classes, with the first argument being of extended class and preceded by "this" keyword. Extension methods have been proposed for inclusion into C++, and have cited C#-style extension methods as inspiration.[2]

In Java, extension methods are added via Manifold, a jar file added to the project's classpath. Similar to C#, a Java extension method is declared static in an @Extension class where the first argument has the same type as the extended class and is annotated with @This. Alternatively, the Fluent plugin allows calling any static method as an extension method without using annotations, as long as the method signature matches.

In Smalltalk, any code can add a method to any class at any time, by sending a method creation message (such as methodsFor:) to the class the user wants to extend. The Smalltalk method category is conventionally named after the package that provides the extension, surrounded by asterisks. For example, when Etoys application code extends classes in the core library, the added methods are put in the *etoys* category.

In Ruby, like Smalltalk, there is no special language feature for extension, as Ruby allows classes to be re-opened at any time with the class keyword to add new methods. The Ruby community often describes an extension method as a kind of monkey patch. There is also a newer feature for adding safe/local extensions to the objects, called Refinements, but it is known to be less used.

In Rust, extension methods do not exist, however for types that the user defines one may arbitrarily add new methods with impl blocks at any point, or impl Trait blocks. It is illegal to put impl blocks on types that are not owned by the user, or if the trait or at least one of the types is not defined in the current crate (called the "orphan rule").[3] This is used to prevent two crates from implementing the same trait for the same type in an incompatible way.

In Swift, the extension keyword marks a class-like construct that allows the addition of methods, constructors, and fields to an existing class, including the ability to implement a new interface/protocol to the existing class.[4]

Extension methods as enabling feature

[edit]

Next to extension methods allowing code written by others to be extended as described below, extension methods enable patterns that are useful in their own right as well. The predominant reason why extension methods were introduced was Language Integrated Query (LINQ). Compiler support for extension methods allows deep integration of LINQ with old code just the same as with new code, as well as support for query syntax which for the moment is unique to the primary Microsoft .NET languages.

using System;

Console.WriteLine(
    new[] { Math.PI, Math.E }
        .Where(d => d > 3)
        .Select(d => Math.Sin(d / 2))
        .Sum()
);
// Output:
// 1

Centralize common behavior

[edit]

However, extension methods allow features to be implemented once in ways that enable reuse without the need for inheritance or the overhead of virtual method invocations, or to require implementors of an interface to implement either trivial or woefully complex functionality.

A particularly useful scenario is if the feature operates on an interface for which there is no concrete implementation or a useful implementation is not provided by the class library author, e.g. such as is often the case in libraries that provide developers a plugin architecture or similar functionality.

Consider the following code and suppose it is the only code contained in a class library. Nevertheless, every implementor of the ILogger interface will gain the ability to write a formatted string, just by including a using MyCoolLogger statement, without having to implement it once and without being required to subclass a class library provided implementation of ILogger.

namespace Wikipedia.Util.Logging;

using System;

public interface ILogger
{
    void Write(string text);
}

public static class LoggerExtensions
{
    public static void Write(this ILogger logger, string format, params object[] args)
    {
        if (logger != null)
        {
            logger.Write(String.Format(format, args));
        }
    }
}

use as :

using MyProject.Util.Logging;

MyLoggerImplementation logger = new();
logger.Write("{0}: {1}", "kiddo sais", "Mam mam mam mam ...");
logger.Write("{0}: {1}", "kiddo sais", "Ma ma ma ma... ");
logger.Write("{0}: {1}", "kiddo sais", "Mama mama mama mama ");
logger.Write("{0}: {1}", "kiddo sais", "Mamma mamma mamma ... ");
logger.Write("{0}: {1}", "kiddo sais", "Elisabeth Lizzy Liz...");
logger.Write("{0}: {1}", "mamma sais", "WHAT?!?!!!");
logger.Write("{0}: {1}", "kiddo sais", "hi.");

Better loose coupling

[edit]

Extension methods allow users of class libraries to refrain from ever declaring an argument, variable, or anything else with a type that comes from that library. Construction and conversion of the types used in the class library can be implemented as extension methods. After carefully implementing the conversions and factories, switching from one class library to another can be made as easy as changing the using statement that makes the extension methods available for the compiler to bind to.

Fluent application programmer's interfaces

[edit]

Extension methods have special use in implementing so called fluent interfaces. An example is Microsoft's Entity Framework configuration API, which allows for example to write code that resembles regular English as closely as practical.

One could argue this is just as well possible without extension methods, but one will find that in practice, extension methods provide a superior experience because less constraints are placed on the class hierarchy to make it work – and read – as desired.

The following example uses Entity Framework and configures the TodoList class to be stored in the database table Lists and defines a primary and a foreign key. The code should be understood more or less as: "A TodoList has key TodoListID, its entity set name is Lists and it has many TodoItem's each of which has a required TodoList".

namespace Wikipedia.Examples;

public class TodoItemContext : DbContext 
{
    public DbSet<TodoItem> TodoItems { get; set; }
    public DbSet<TodoList> TodoLists { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<TodoList>()
            .HasKey(e => e.TodoListId)
            .HasEntitySetName("Lists")
            .HasMany(e => e.Todos)
            .WithRequired(e => e.TodoList);
    }
}

Productivity

[edit]

Consider for example IEnumerable noting its simplicity – there is one method that is essentially the basis of LINQ. There are many implementations of this interface in Microsoft .NET. It would have been burdensome to require each of these implementations to implement the series of methods that are defined in the System.Linq namespace to operate on IEnumerables. This would have required those other than Microsoft to consider using IEnumerable to also implement those methods, which would have been inefficient given the widespread use of this interface. By implementing the one method of this interface, LINQ can be used essentially immediately. In most cases IEnumerable's GetEnumerator method is delegated to a private collection, list or array's GetEnumerator implementation.

namespace Wikipedia.Examples;

using System;
using System.Collections.Generic;

public class BankAccount : IEnumerable<decimal> 
{
    private List<Tuple<DateTime, decimal>> credits; // assumed all negative
    private List<Tuple<DateTime, decimal>> debits; // assumed all positive

    public IEnumerator<decimal> GetEnumerator() 
    {
        IEnumerator<decimal> query = from dc in debits.Union(credits) 
            orderby dc.Item1 // Date
            select dc.Item2; // Amount
    
        foreach (decimal amount in query)
        {
            yield return amount;
        }
    }
}
// given an instance of BankAccount called ba and a using System.Linq on top of the current file,
// one could now write ba.Sum() to get the account balance, ba.Reverse() to see most recent transactions first,
// ba.Average() to get the average amount per transaction, etcetera - without ever writing down an arithmetic operator

Performance

[edit]

That said, additional implementations of a feature provided by an extension method can be added to improve performance, or to deal with differently implemented interface implementations, such as providing the compiler an implementation of IEnumerable specifically for arrays (in System.SZArrayHelper), which it will automatically choose for extension method calls on array typed references, since their argument will be more specific (this T[] value) than the extension method with the same name that operates on instances of the IEnumerable interface (this IEnumerable value).

Alleviating the need for a common base class

[edit]

With generic classes, extension methods allow implementation of behavior that is available for all instantiations of the generic type without requiring them to derive from a common base class, and without restricting the type parameters to a specific inheritance branch. This is advantageous since the situations where this argument holds require a non-generic base class to implement the shared feature – which then requires the generic subclass to perform boxing and/or casts whenever the type used is one of the type arguments.

Conservative use

[edit]

Regarding preferring extension methods over other means of achieving reuse and proper object-oriented design, extension methods may clutter the automatic completion features of code editors, such as Visual Studio's IntelliSense, hence they should either be in their own namespace to allow the developer to selectively import them. Alternatively, they should be defined on a type that is specific enough for the method to appear in IntelliSense only when highly relevant and given the above, consider that they might be hard to find should the developer expect them, but miss them from IntelliSense due to a missing using statement, since the developer may not have associated the method with the class that defines it, or even the namespace in which it lives – but rather with the type that it extends and the namespace that type lives in.

The problem

[edit]

In programming, situations arise where it is necessary to add functionality to an existing class—for instance by adding a new method. Normally the programmer would modify the existing class's source code, but this forces the programmer to recompile all binaries with these new changes and requires that the programmer be able to modify the class, which is not always possible, for example when using classes from a third-party assembly. This is typically worked around in one of three ways, all of which are somewhat limited and unintuitive:[citation needed]

  1. Inherit the class and then implement the functionality in an instance method in the derived class.
  2. Implement the functionality in a static method added to a helper class.
  3. Use aggregation instead of inheritance.

Current C# solutions

[edit]

The first option is in principle easier, but it is limited because many classes restrict inheritance of certain members or forbid it completely. This includes sealed class and the different primitive data types in C# such as int, float and string. Another option does not share these restrictions, but it may be less intuitive as it requires a reference to a separate class instead of directly using the methods of the class in question.

As an example, consider a need of extending the string class with a new reverse method whose return value is a string with the characters in reverse order. Because the string class is a sealed type, the method would typically be added to a new utility class in a manner similar to the following:

string x = "some string value";
string y = Utility.Reverse(x);

This may, however, become increasingly difficult to navigate as the library of utility methods and classes increases, particularly for newcomers. The location is also less intuitive because, unlike most string methods, it would not be a member of the string class, but would be in a different class. A better syntax would therefore be the following:

string x = "some string value";
string y = x.Reverse();

Current VB.NET solutions

[edit]

In most ways, the VB.NET solution is similar to the C# solution above. However VB.NET has an advantage in that it allows members to be passed to the extension by reference (C# only allows by value). Allowing for the following;

Dim x As String = "some string value"
x.Reverse()

Because Visual Basic allows the source object to be passed in by reference it is possible to make changes to the source object directly, without need to create another variable. It is also more intuitive as it works in a consistent fashion to existing methods of classes.

Extension methods

[edit]

The new language feature of extension methods in C# 3.0, however, makes the latter code possible. This approach requires a static class and a static method, as follows.

namespace Wikipedia.Examples;

using System;

public static class Utility
{
    public static string Reverse(this string input)
    {
        char[] chars = input.ToCharArray();
        Array.Reverse(chars);
        return new String(chars);
    }
}

In the definition, the modifier 'this' before the first argument specifies that it is an extension method (in this case to the type 'string'). In a call, the first argument is not 'passed in' because it is already known as the 'calling' object (the object before the dot).

The major difference between calling extension methods and calling static helper methods is that static methods are called in prefix notation, whereas extension methods are called in infix notation. The latter leads to more readable code when the result of one operation is used for another operation.

With static methods
HelperClass.Operation2(HelperClass.Operation1(x, arg1), arg2)
With extension methods
x.Operation1(arg1).Operation2(arg2)

Naming conflicts in extension methods and instance methods

[edit]

In C# 3.0, both an instance method and an extension method with the same signature can exist for a class. In such a scenario, the instance method is preferred over the extension method. Neither the compiler nor the Microsoft Visual Studio IDE warns about the naming conflict. Consider this C# class, where the GetAlphabet() method is invoked on an instance of this class:

namespace Wikipedia.Examples;

using System;

class AlphabetMaker 
{
    // When this method is implemented, it will shadow the implementation in the ExtensionMethods class.
    public void GetAlphabet()
    {
        Console.WriteLine("abc");
    }
}

static class ExtensionMethods
{
    //This will only be called if there is no instance method with the same signature.
    public static void GetAlphabet(this AlphabetMaker am)
    {
        Console.WriteLine("ABC");
    }
}

The result of invoking GetAlphabet() on an instance of AlphabetMaker if only the extension method exists:

ABC

The result if both the instance method and the extension method exist:

abc

See also

[edit]

References

[edit]
  1. ^ "Extension Methods". Microsoft. Retrieved 2008-11-23.
  2. ^ Coe, Jonathan; Orr, Roger. "Extension methods for C++" (PDF). open-std.org. WG21. Retrieved 4 February 2025.
  3. ^ The Rust Reference (25 February 2025). "Implementations". doc.rust-lang.org. The Rust Reference.
  4. ^ "Extensions – The Swift Programming Language (Swift 5.7)". docs.swift.org. Retrieved 2022-06-12.
[edit]

Source: Wikipedia. Article content is retrieved live through the MediaWiki API.

No preview image
Wikipedia

Entry point

In computer programming, an entry point is the place in a program where the execution of a program begins, and where the program has access to command line arguments. To start a program's execution, the loader or operating system passes control to its entry point. (During booting, the operating system itself is the program). This marks the transition from load time (and dynamic link time, if present) to run time. For some operating systems and programming languages, the entry point is in a runtime library, a set of support functions for the language. The library code initializes the program and then passes control to the program proper. In other cases, the program may initialize the runtime library itself. In simple systems, execution begins at the first statement, which is common in interpreted languages, simple executable formats, and boot loaders. In other cases, the entry point is at some other known memory address which can be an absolute address or relative address (offset). Alternatively, execution of a program can begin at a named point, either with a conventional name defined by the programming language or operating system or at a caller-specified name. In many C-family languages, this is a function called main; as a result, the entry point is often known as the main function. In JVM languages, such as Java, the entry point is a static method called main; in CLI languages such as C# the entry point is a static method named Main.

MORE →
No preview image
Wikipedia

Interface (Java)

An interface in the Java programming language is an abstract type that is used to declare a behavior that classes must implement. They are similar to protocols. Interfaces are declared using the interface keyword, and may only contain method signature and constant declarations (variable declarations that are declared to be both static and final). All methods of an Interface do not contain implementation (method bodies) as of all versions below Java 8. Starting with Java 8, default and static methods may have implementation in the interface definition. Then, in Java 9, private and private static methods were added. At present, a Java interface can have up to six different types. Such interfaces exist in C#. Interfaces cannot be instantiated, but rather are implemented. A class that implements an interface must implement all of the non-default methods described in the interface, or be an abstract class. Object references in Java may be specified to be of an interface type; in each case, they must either be null, or be bound to an object that implements the interface. One benefit of using interfaces is that they simulate multiple inheritance. All classes in Java must have exactly one base class, the only exception being java.lang.Object (the root class of the Java type system); multiple inheritance of classes is not allowed. However, an interface may inherit multiple interfaces and a class may implement multiple interfaces.

MORE →
No preview image
Wikipedia

Initialization-on-demand holder idiom

In software engineering, the initialization-on-demand holder (design pattern) idiom is a lazy-loaded singleton. In all versions of Java, the idiom enables a safe, highly concurrent lazy initialization of static fields with good performance. The implementation of the idiom relies on the initialization phase of execution within the Java Virtual Machine (JVM) as specified by the Java Language Specification (JLS). When the class Singleton is loaded by the JVM, the class goes through initialization. Since the class does not have any static variables to initialize, the initialization completes trivially. The static class definition Holder within it is not initialized until the JVM determines that Holder must be executed. The static class Holder is only executed when the static method instance() is invoked on the class Singleton, and the first time this happens the JVM will load and initialize the Holder class. The initialization of the Holder class results in static variable INSTANCE being initialized by executing the (private) constructor for the outer class Singleton. Since the class initialization phase is guaranteed by the JLS to be sequential, i.e., non-concurrent, no further synchronization is required in the static instance() method during loading and initialization. And since the initialization phase writes the static variable INSTANCE in a sequential operation, all subsequent concurrent invocations of the instance() will return the same correctly initialized INSTANCE without incurring any additional synchronization overhead.

MORE →
No preview image
Wikipedia

Extension method

In object-oriented computer programming, an extension method is a method added to an object after the original object was compiled. The modified object is often a class, a prototype, or a type. Extension methods are features of some object-oriented programming languages. There is no syntactic difference between calling an extension method and calling a method declared in the type definition. Not all languages implement extension methods in an equally safe manner, however. For instance, languages such as C#, Java (via Manifold, Lombok, or Fluent), and Kotlin don't alter the extended class in any way, because doing so may break class hierarchies and interfere with virtual method dispatching. Instead, these languages strictly implement extension methods statically and use static dispatching to invoke them.

MORE →
TOPIC OF THE DAY

Greenwood / Black Wall Street

Before the 1921 destruction of Tulsa’s Greenwood District, Black residents had created a remarkable center of business and community life. The district included stores, professional offices, entertainment venues and homes owned by Black citizens. Understanding Greenwood means learning what was built—not only what was burned.

MORE →
TRIVIA QUESTION OF THE DAY

Which Black woman became the first elected to the United States Congress?

Shirley Chisholm, elected in 1968.