Abstraction and information hiding - abstraction

Abstraction means hiding 'implementation details'..... So the goal of abstraction is to achieve information hiding?? And what is hidden in Information hiding if not implementation details??
And how abstraction is a technique to information hiding?

The goal of abstraction is not to hide information in the sense of variable values, that would be encapsulation.
Abstraction's only goal is allow programmers to use an algorithm or concept without understanding it. Information hiding may be a by-product of this but it is not its goal.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/* Example of Abstratcion: An application for mobile manufacturing company - Every phone must have to implement caller
* and sms feature but it depends on company to company (or model to model) if they want to include other features or not
* which are readily available , you just have to use it without knowing its implementation (like facebook in this example).
*/
namespace AbstractTest
{
public abstract class feature
{
public abstract void Caller();
public abstract void SMS();
public void facebook()
{
Console.WriteLine("You are using facebook");
}
}
public class Iphone : feature
{
public override void Caller()
{
Console.WriteLine("iPhone caller feature");
}
public override void SMS()
{
Console.WriteLine("iPhone sms feature");
}
public void otherFeature()
{
facebook();
}
}
public class Nokia : feature
{
public override void Caller()
{
Console.WriteLine("Nokia caller feature");
}
public override void SMS()
{
Console.WriteLine("Nokia sms feature");
}
}
class Program
{
static void Main(string[] args)
{
Iphone c1 = new Iphone();
c1.Caller();
c1.SMS();
c1.otherFeature();
Nokia n1 = new Nokia();
n1.Caller();
n1.SMS();
Console.ReadLine();
}
}
}

Related

Hide responses of model annotations in production asp.net

Hi all I use [Required] among other annotations. When the application is in production I would like to change the default messages or better yet send a simple http response.
I noticed that some people do this
[Required(ErrorMessage = "res")] I have many fields. I don't want to do them manually one by one, but I was wondering how is it possible to do this even though Required has a single no arguments constructor?
Thank you
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace MyCoolApplication
{
public class ValidationActionFilter : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext context)
{
if (!context.ModelState.IsValid)
{
context.Result = ((ControllerBase)context.Controller).Problem();
}
}
}
}

How do Interfaces promote code reusablity?

A simple interview question.
How do interfaces help with code reusablity?
interfaces allows you to separate the implementation from the information the calling class cares about. This enables you to de-couple your classes from having intimate knowledge of classes it depends on.
Given the following interface:
public interface IRepository<T> {
void Save(T entity);
void Update(T entity);
void Delete(T entity);
}
A dependent class can be programmed against said interface and be "shielded" from the details.
public class SomeService {
private IRepository<Contact> _contactRepo;
public SomeService(IRepository<Contact> contactRepo){
_contactRepo = contactRepo;
}
}
Utilizing this pattern enables you to create different implementations of said interface:
public class LinqToSqlRepository<Contact> : IRepository<Contact>
{ /* ... */ }
public class EntityFrameworkRepository<Contact> : IRepository<Contact>
{ /* ... */ }
public class NHibernateRepository<Contact> : IRepository<Contact>
{ /* ... */ }
An interface decouples the consumer from the implementation details of a class. This helps enables reusability because the class implementing an interface can change, without needing to change the code consuming the implementation.
That's very confusing, maybe an example helps
public interface IUserAuthentication
{
public bool Authenticate(string name, string password);
}
Now I will write the consumer, it doesn't care how authentication is performed, it simply knows that it can authenticate users.
public class Consumer
{
private IUserAutentication _auth;
public Consumer(IUserAuthentication auth)
{
_auth = auth;
}
public void Working(string username, string password)
{
if (!_auth.Authenticate(username, password))
{
throw new Exception("error!");
}
}
}
The code above will work regardless of the implementation of the IUserAuthentication service. This is one way to reuse code.
Now I can implement the IUserAuthentication interface
public class AuthenticateJasons : IUserAuthentication
{
public bool Authenticate(string username, string password)
{
return username == "Jason";
}
}
public class AuthenticateNoone: IUserAuthentication
{
public bool Authenticate(string username, string password)
{
return false;
}
}
The point is that these implementations are irrelevant as far as the consumer is concerned. Also, this question is not related to ASP.NET the web framework. This is really a language/platform/framework agnostic question. The answer is the same regardless of the language you choose to implement with.
It is the Open and Close Principle, one of the important law of S.O.L.I.D Principles.
its idea is easy to change with minimum changes in the existing code. And ultimately helps with unit testing.
http://www.oodesign.com/design-principles.html

Simplest approach for applying the MVP pattern on a Desktop (WinForms) and Web (ASP.NET) solution

Having almost no architectural experience I'm trying to design a DRY KISS solution for the .NET 4 platform taking an MVP approach that will eventually be implemented as a Desktop (WinForms) and Web (ASP.NET or Silverlight) product. I did some MVC, MVVM work in the past but for some reason I'm having difficulties trying to wrap my head around this particular one so in an effort to get a grip of the pattern I've decided to start with the simplest sample and to ask you guys for some help.
So assuming a quite simple Model as follows (in practice it'd most definitely be a WCF call):
internal class Person
{
internal string FirstName { get; set; }
internal string LastName { get; set; }
internal DateTime Born { get; set; }
}
public class People
{
private readonly List<Person> _people = new List<Person>();
public List<Person> People { get { return _people; } }
}
I was wondering:
What would be the most generic way to implement its corresponding View/Presenter triad (and helpers) for say, a Console and a Forms UI?
Which of them should be declared as interfaces and which as abstract classes?
Are commands always the recommended way of communication between layers?
And finally: by any chance is there a well-docummented, testeable, light framework to achieve just that?
I've written a number of apps that require a GUI and a winforms UI, the approach I have typically taken to implementing MVP is to create a generic view interface (you can subclass this for more specific views) and a controllerbase class which is given a view. You can then create different view implementations which inherit from the IView (or more specific view) interface
interface IView
{
event EventHandler Shown;
event EventHandler Closed;
void ShowView(IView parentView);
void CloseView();
}
class ControllerBase<T> where T: IView
{
private T _view;
public ControllerBase(T view)
{
_view = view;
}
public T View
{
get { return _view; }
}
public void ShowView(IView owner)
{
_view.ShowView(owner);
}
public void ShowView()
{
ShowView(null);
}
public void CloseView()
{
_view.CloseView();
}
}
Heres an example of how it would work in a specific case
interface IPersonView: IView
{
event EventHandler OnChangeName;
string Name { get; set; }
}
class PersonController: ControllerBase<IPersonView>
{
public PersonController(string name,IPersonView view) : base(view)
{
View.Name = name;
View.OnChangeName += HandlerFunction;
}
private void HandlerFunction(object sender, EventArgs e)
{
//logic to deal with changing name here
}
}
To implement this view in winforms, just make sure your form inherits from IPersonView and implements all the required properties/events and you're good to go. To instantiate the view/controller you'd do something like the following
PersonForm form = new PersonForm();
PersonController controller = new PersonController("jim",form);
controller.ShowView();

UnityContainer: Conditional Logic upon resolving

I have an interface with 3 different implementations. I register the 3 implementations as named aliases in the Web.config of the Web application using Unity Container.
Is there a way using Unity, to resolve one of the registered instance, based on some logic. the logic includes contacting a DB to decide on which implementation to be resolved.
Appreciate your help.
Regards
Bilal
You can implement the logic in an abstract factory and inject it:
public interface IMyInterface { }
public interface IMyInterfaceFactory {
IMyInterface GetMyInterface();
}
public class MyInterfaceFactory : IMyInterfaceFactory {
private readonly IUnityContainer _container;
public MyInterfaceFactory(IUnityContainer container) {
_container = container; }
IMyInterface GetMyInterface() {
var impName = Get_implementation_name_from_db();
return container.Resolve<IMyInterface>(impName);
}
}
You can create a 'router' implementation that knows how to route the requests to one of the other implementations:
// Here is a possible implementation of the router. There are
// of course many ways to do this.
public class MyRouterImpl : IMyInterface
{
List<IMyInterface> implementations = new List<IMyInterface>();
public MyRouterImpl(MyImpl1 i1, MyImpl2 i2, MyImpl3 i3)
{
this.implementations.Add(i1);
this.implementations.Add(i2);
this.implementations.Add(i3);
}
void IMyInterface.Method()
{
int indexOfImplementationToExecute =
GetIndexOfImplementationToExecute();
IMyInterface impl =
this.implementations[indexOfImplementationToExecute];
impl.Method();
}
}

How can I aggregate interfaces into with castle dynamic proxy

I would like to allow for declarative mixin management in my codebase. I would like to declare an interface like
public interface IMyRepo : IRepository, ICanFindPeopleByName, ICantSing {}
So my classes can consume only the bits of the data access layer they need. In my IoC container I would like to aggregate the implementations of these interfaces into a single instance. However when I do things similar to the referenced threads, the generator throws an exception stating that interfaces are implemented in multiple places. What can I do, other than implementing my own interceptor and passing through?
Relevant Threads:
Help Migrating mixins from Castle.DynamicProxy to DynamicProxy2.
Windsor MixIn is a Singleton?
Better Example (wall of code)
public interface IIceCream {
void Eat();
}
public class IceCream : IIceCream {
public void Eat() { Console.WriteLine("Yummy!"); }
}
public interface ICake {
void NomNom();
}
public class Cake : ICake {
public void NomNom() { Console.WriteLine("Cakey!"); }
}
public interface ISprinkles {
void Oogle();
}
public class Sprinkles : ISprinkles {
public void Oogle(){ Console.WriteLine("Its Pretty!");}
}
public interface IIceCreamWithCakeAndSprinkles : IIceCream, ICake, ISprinkles {}
public class Program
{
public static void Main()
{
var gen = new ProxyGenerator();
var options = new ProxyGenerationOptions();
options.AddMixinInstance(new IceCream());
options.AddMixinInstance(new Cake());
options.AddMixinInstance(new Sprinkles());
var result =
gen.CreateClassProxy(typeof (object), new[] {typeof (IIceCreamWithCakeAndSprinkles)}, options) as IIceCreamWithCakeAndSprinkles;
}
}
throws
InvalidMixinConfigurationException: "The mixin IceCream adds the interface 'ConsoleApplication1.IIceCream' to the generated proxy, but the interface already exists in the proxy's additional interfaces. A mixin cannot add an interface already implemented in another way."
Update to Dynamic Proxy 2.2 or 2.5 It is more permissive and it will let the mixin own the interface and ignore that it was passed again as "additional interface".

Resources