ILogger<T>? defaulting to null vs ILogger<T> defaulting to NullLogger<T> - c#

Take the following two classes:
public class PersonA
{
private readonly ILogger<PersonA> _logger;
public PersonA() : this(new NullLogger<PersonA>())
{}
public PersonA(ILogger<PersonA> logger)
{
_logger = logger;
}
public void SomeMethod()
{
_logger.LogDebug("SomeMethod invoked");
}
}
public class PersonB
{
private readonly ILogger<PersonB>? _logger;
public PersonB(ILogger<PersonB>? logger = null)
{
_logger = logger;
}
public void SomeMethod()
{
_logger?.LogDebug("SomeMethod invoked");
}
}
The way that ILogger<T> is passed is very similar in both and both approaches work, but is there any reason why you'd favour ILogger<T>? defaulting to null over two ctors one defaulting to NullLogger<T> and ensuring that _logger is never null or vice-versa?
Are any differences in performance?

As pointed out by one comment, there is so little difference in tearms of performance and object allocation that I would actually avoid to compare these two approaches in tearms of performance.
I would instead suggest the following considerations:
having two constructors is worst in terms of design. That will make creating your object harder, because the object creator has to choose between the two and have to understand the different semantic. It is much better having one and only one way to create an object: that's simpler and there is no ambiguity about the way the object should be created
as long as possible I would avoid handling null values. Code using objects that can potentially be null is harder to maintain, because if you accidentally forget the ? operator when you refactor your code you will get a NullReferenceException at runtime. You would need to write and maintain additional unit tests for the null case, in order to be sure you didn't forget a ? somewhere in your code.
Based on these two points, a better design is the following:
have a class with only one constructor
do not allow the _logger field to be nullable, that is it's type should be ILogger<Person> instead of ILogger<Person>?. In cases when you don't care about logging, use the null object pattern and inject an instance of NullLogger<Person> in the constructor (instead of using a null reference).
As a final note do not instantiate NullLogger<T>. Use, instead, the NullLogger<T>.Instance static field. By doing so, you will access to a shared cached instance of the class and you will avoid to allocate a new object (it's fine to do so for stateless classes like NullLogger<T>). This is good in tearms of memory usage and garbage collector pressure.
Final design of the class is the following:
public class Person
{
private readonly ILogger<Person> _logger;
public Person(ILogger<Person> logger)
{
// guard against null
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public void SomeMethod()
{
_logger.LogDebug("SomeMethod invoked");
}
}
// if you don't care about logging
var person = new Person(NullLogger<Person>.Instance);

Related

Why constructors if curl braces

What is a sense to create set of constructors if there is still possibility to initiate any set of fields for a class using curly braces? Never thought about that before but from my experience i could make few constructors to secure the way class can be constructed. Nevertheless every time curly bracets can be used which to me is something like a hack overcoming constructors. Am I missing something here?
If you are allowing the fields and properties to be set by the caller, yes, there is no difference. But the constructor is not only about setting fields, it holds the logic to instantiate an object.
If you want the object to be immutable and be changed only by itself, you should use readonly fields and read-only properties.
Read-only properties are declared by not providing a setter, or more simply, the set keyword.
An example:
public class YourClass
{
readonly string readonlyField;
public int ImmutableIntProperty {get;}
public YourClass(string field, int value)
{
readonlyField = field;
ImmutableIntProperty = value;
}
}
Constructors are not only for object initialization, but we can also use it to inject dependencies.
For Example: we can inject the dependency of Logger class to Constructor to use it throughout the class.
public class Demo
{
private readonly ILogger<Demo> _logger;
public Demo(ILogger<Demo> logger)
{
// Use _logger throughout the class
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public void Log()
{
// _logger.Log(message);
}
}
NOTE: Some dependencies are resolved by .Net itself, but in case of custom types we need to resolve dependency by our self. This will help to to achieve loose coupling between types and is extensively used in multi tier projects.

Interface implementation with only empty methods

I'm using log4net in an application for logging.
I want to avoid a discussion about implementing a logging facade, but essentially, I'm creating some classes which will allow an ILog implementation to be injected via the constructor. Eg:
abstract class MigratorBase<T> : IMigrator<T>
{
private ILog logger;
public MigratorBase(ILog logger)
{
this.logger = logger;
}
}
I also would like to provide a default constructor on the class, which if called, essentially disables logging (or logs to nothing). Instead of scattering fragments of code that check if the logger is null, such as this:
if (this.logger != null)
Log.DebugFormat("Connecting to {0}", this.href);
I thought a better way to accomplish this functionality would be to assign an implementation of ILog that was purely empty methods. I could call it a NullLog, and would look similar to this:
class NullLog : ILog
{
public void Debug(object message, Exception exception) { }
public void Debug(object message) { }
public void DebugFormat(IFormatProvider provider, string format, params object[] args) { }
...
...
}
and then in the default constructor I could assign an object of this type to the class's private member, as such:
abstract class MigratorBase<T> : IMigrator<T>
{
private ILog logger;
public MigratorBase(ILog logger)
{
this.logger = logger;
}
public MigratorBase()
{
this.logger = new NullLog();
}
}
This approach seems more object oriented to me, so I think I like it, but googling seems to reveal people suggesting that it's a bad idea to implement an interface with empty methods.
Can anyone suggest why the above might be a bad idea? Or is it in fact an ok idea?
What you describe is called the Null Object pattern. Martin Fowler coined this term and explains it thoroughly in the book Patterns of Enterprise Application Architecture.
I think this is a great pattern to remove all the if-conditions in the code to check for not null. A downside could be that you have to explain a pattern in you development team and maybe add a comment about not adding functionality inside your NullLog class. Otherwise I couldn’t find a downside with this pattern.

Singleton Alternative - is it equivalent?

I know that the standard singleton pattern is as follows:
Original
public class Singleton1
{
public static Singleton1 _Instance;
public static Singleton1 Instance
{
get
{
if (_Instance == null)
{
_Instance = new Singleton1();
}
return _Instance;
}
}
private Singleton1()
{
}
}
But it seems like this code is unnecessary. To me, you could accomplish the same thing with either of the following simple design patterns:
Version 2
public class Singleton2
{
public static readonly Singleton2 Instance = new Singleton2();
private Singleton2()
{
}
}
Version 3
public class Singleton3
{
static Singleton3()
{
}
}
To me, it seems like version 2 is the superior method of doing this because it allows you to pass in parameters (or not) yet still have a finite number of instance. My application is fairly latency/performance sensitive - do any of these patterns have a performance gain?
It would seem that while it will longer to access each one the first time because the object is being created. Also, it would seem that the original one is ever so slightly slower because it must check to see whether its backing field is null every time something else accesses it.
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
private Singleton()
{
}
}
Fast, clean, thread-safe.
One problem with singletons implemented as static instances is that they make testing and mocking more difficult.
See this scenario:
public void BusinessLogicMethod()
{
var initialValue = MySingleton.Instance.GetInitialValue();
var processedValue = initialValue + specialSomething + businessLogic;
MySingleton.Instance.SaveProcessedValue(processedValue);
}
Now, let's say I want to write a unit-test for this method. Ideally, I want to write a test that specifies input and output and tests only the business logic. But with a static singleton, the method's implementation is tied to the singleton's implementation. Can I set the InitialValue easily at the beginning of the test, or is it dependent on other factors/DB access/whatever?
However, if I use a non-static singleton, coupled with some dependency injection or service locator pattern, I can build my function like this:
public void BusinessLogicMethod()
{
var singleton = ServiceLocator.Resolve<MySingleton>();
var processedValue = singleton.InitialValue + specialSomething + businessLogic;
singleton.SaveProcessedValue(processedValue);
}
and my test can go like this, using vaguely Moq-like mock syntax:
public void TestBusinessLogic()
{
MySingleton fakeSingleton = new Mock<MySingleton>();
fakeSingleton.Setup(s => s.InitialValue).Returns(5);
// Register the fake in the ServiceLocator
ServiceLocator.Register<MySingleton>(fakeSingleton.Object);
// Run
MyBusinessMethod();
// Assert
fakeSingleton.Verify (s => s.SaveProcessedValue()).Called(Exactly.Once);
}
without worrying about the REAL singleton implementation.
Singleton2 is not the same as Singleton1 as the Instance is not "lazy" evaluated. In Singleton1, Instance is created only when it is accessed and from then on the same one is used. In SingleTon2, the Instance is initialized with the class and before being actually accessed.
My favourite singleton implementation is this one:
http://www.codeproject.com/Articles/14026/Generic-Singleton-Pattern-using-Reflection-in-C
Make sure your .ctor is not public, which is the most common mistake, then, it is safely/fully reusable.
(I need to have a close look at Peter Kiss' one which looks nice too)
To answer your performance question, the time it takes to check whether the private field is null is negligible. Therefore I wouldn't be worrying about how it is implemented with regards to performance here.

How to deal with scope-natured services like transactions in a DI and IOC environment

Suppose that your code is properly designed for DI and IOC through constructor injection of any dependencies. Then whether an IOC container or DI-by-hand is used or not at the composition root doesn't matter much for this problem. I think.
Anyway, I find myself over and over again in a mental struggle with how I should best deal with scope-based services, like transactions or other obviously transient operations. There are constraints that I want to abide to:
Don't let dependency interfaces be IDisposable - it's a leaky abstraction that only the actual implementing type (and the fiddler sitting at the composition root) should care about.
Don't use static service locator types deep down the graph to resolve a dependency - only inject and resolve through the constructor.
Don't pass the IOC container, if any, as a dependency down the graph.
To be able to use using, we need IDisposable, but since a dependency interface shouldn't be IDisposable, how do you get around it to get scoped behavior?
In cases like this I would inject a service factory that creates those scoped services and let the service interface derive from IDisposable. This way the factory would be responsible to create the appropriate service instances and the only point that decides which service implementation to return. You would not need to inject the scoped service anywhere.
public interface ITransaction : IDisposable
{
}
public interface ITransactionFactory
{
ITransaction CreateTransaction();
}
public class Foo
{
private readonly ITransactionFactory transactionFactory;
public Foo(ITransactionFactory transactionFactory)
{
this.transactionFactory = transactionFactory;
}
public void DoSomethingWithinTransaction()
{
using(ITransaction transaction = this.transactionFactory.CreateTransaction())
{
DoSomething();
}
}
}
Most IoC containers today have substantial built-in support for units of work of this nature.
In Autofac, the mechanism that best fits your requirements is the Owned<T> relationship type. You can see it in action (and get some more material) via this article.
Hope this helps,
Nick
Roll your own "garbage collector" maybe? Something that periodically checks IsComplete and/or an LastAccessed attribute of a Dictionary<Transaction> and wastes the "old" ones. It's "a walking memory leak" but either you clean-up explicitly (like through IDisposable) or you workout how to clean-up automatically.
There may be an AOP solution to kicking-off the "gc"... a commit/rollback sounds like a good place to cut... and maybe you won't even need a GC at all... just cleanup the transaction on the way back-up the callstack from commit or rollback.
Good luck with it. I'll be interested to see what solutions (and ideas) other people come-up with.
Cheers. Keith.
I guess another alternative you could use is to wrap your instances with a disposable type, that way it could automatically handle the disposal of the type regardless of whether the type is actually disposable. E.g, I could define something like:
public class DisposableWrapper<T> : IDisposable
{
private readonly T _instance;
private readonly IDisposable _disposable;
public DisposableWrapper(T instance)
{
_instance = instance;
_disposable = instance as IDisposable;
}
public void Dispose()
{
if (_disposable != null)
_disposable.Dispose();
}
public static implicit operator T(DisposableWrapper<T> disposableWrapper)
{
return disposableWrapper._instance;
}
}
(Hopefully with a bit more error handling!)
Given that I know at the point of disposal whether the type is disposable, I can call it accordingly. I can also provide an implicit operator to cast back to the inner type from it. With the above, and a nifty extension method:
public static class DisposableExtensions
{
public static DisposableWrapper<T> Wrap<T>(this T instance)
{
return new DisposableWrapper<T>(instance);
}
}
Let's imagine that I have a service I am injecting into a type, it could be:
public interface IUserService
{
IUser GetUser();
}
I could potentially do something like:
public HomeController(IUserService service)
{
using (var disposable = service.Wrap())
{
var user = service.GetUser();
// I can even grab it again, implicitly.
IUserService service2 = disposable;
}
}
Now regardless of whether that concrete implementation of IUserService is disposable or not, I can still safely work on the assumption that it doesn't matter.
Another quick console example:
class Program
{
static void Main(string[] args)
{
using (var instance = new ClassA().Wrap())
{
ClassA instanceA = instance;
}
using (var instance = new ClassB().Wrap())
{
ClassB instanceB = instance;
}
Console.ReadKey();
}
}
public class ClassA
{
}
public class ClassB : IDisposable
{
public void Dispose()
{
Console.Write("Disposed");
}
}

IoC and constructor over-injection anti-pattern resolution

This question is a result of a post by Jeffery Palermo on how to get around branched code and dependency injection http://jeffreypalermo.com/blog/constructor-over-injection-anti-pattern/
In his post, Jeffery has a class (public class OrderProcessor : IOrderProcessor) that takes 2 interfaces on the constructor. One is a validator IOrderValidator and an IOrderShipper interface. His method code branches after only using methods on the IOrderValidator interface and never uses anything on the IOrderShipper interface.
He suggests creating a factory that will call a static method to get the delegate of the interface. He is creating a new object in his refactored code which seems unnecessary.
I guess the crux of the issue is we are using IoC to build all our objects regardless if they're being used or not. If you instantiate an object with 2 interfaces and have code that could branch to not use one of them, how do you handle it?
In this example, we assume _validator.Validate(order) always returns false and the IOrderShipper.Ship() method is never called.
Original Code:
public class OrderProcessor : IOrderProcessor
{
private readonly IOrderValidator _validator;
private readonly IOrderShipper _shipper;
public OrderProcessor(IOrderValidator validator, IOrderShipper shipper)
{
_validator = validator;
_shipper = shipper;
}
public SuccessResult Process(Order order)
{
bool isValid = _validator.Validate(order);
if (isValid)
{
_shipper.Ship(order);
}
return CreateStatus(isValid);
}
private SuccessResult CreateStatus(bool isValid)
{
return isValid ? SuccessResult.Success : SuccessResult.Failed;
}
}
public class OrderShipper : IOrderShipper
{
public OrderShipper()
{
Thread.Sleep(TimeSpan.FromMilliseconds(777));
}
public void Ship(Order order)
{
//ship the order
}
}
Refactored Code
public class OrderProcessor : IOrderProcessor
{
private readonly IOrderValidator _validator;
public OrderProcessor(IOrderValidator validator)
{
_validator = validator;
}
public SuccessResult Process(Order order)
{
bool isValid = _validator.Validate(order);
if (isValid)
{
IOrderShipper shipper = new OrderShipperFactory().GetDefault();
shipper.Ship(order);
}
return CreateStatus(isValid);
}
private SuccessResult CreateStatus(bool isValid)
{
return isValid ? SuccessResult.Success : SuccessResult.Failed;
}
}
public class OrderShipperFactory
{
public static Func<IOrderShipper> CreationClosure;
public IOrderShipper GetDefault()
{
return CreationClosure(); //executes closure
}
}
And here is the method that configures this factory at start-up time (global.asax for ASP.NET):
private static void ConfigureFactories()
{
OrderShipperFactory.CreationClosure =
() => ObjectFactory.GetInstance<IOrderShipper>();
}
I just posted a rebuttal of Jeffrey Palermos post.
In short, we should not let concrete implementation details influence our design. That would be violating the Liskov Substitution Principle on the architectural scale.
A more elegant solution lets us keep the design by introducing a Lazy-loading OrderShipper.
I'm running late for a meeting, but a few quick points...
Sticking to the code branching of using only one dependency, there are two branches to propose:
Applying DDD practices, you would not have an OrderProcessor with a dependency on IOrderValidator. Instead, you'd make the Order() entity be responsible for its own validation. Or, stick to your IOrderValidator, but have its dependency within the OrderShipper() that is implemented - since it will return any error codes.
Ensure the dependencies being injected are constructed using a Singleton approach (and configured as Singleton in the IoC container being used). This resolves any memory concerns.
Like someone else that mentioned here, the point is to break the dependency on concrete classes and loosely couple the dependencies using Dependency Injection with some IoC container in use.
This makes future refactoring and swapping out legacy code far easier on a grand scale by limiting the technical debt incurred in the future. Once you have a project near 500,000 lines of code, with 3000 unit tests, you'll know first hand why IoC is so important.

Categories