How do I make my Linq to Sql entity expose an interface? - linq-to-sql

Using Nerd Dinner as an example:
private NerdDinnerDataContext db = new NerdDinnerDataContext();
public IQueryable<Dinner> FindAllDinners()
{
return db.Dinners;
}
Is it not bad practice to directly expose the entity class Dinner here? I think it is better for the repository to return an IDinner.
So my question is, how can I make the auto-generated entity classes expose my interface?

As far as I know, the only way would be to modify the template from which the code is generated. Another possibility is partial classes. The code generator creates partial classes. You could create another partial class that contains the interface you want. I believe this will work.

Related

Question on class implementation with interface

I have created the following classes for sharing images. They implement an interface, but I need a way of switching between them with user interaction. I've done it the following way:
As you can see, service 1 and service 2 implement iSharingServices, and inherit from PolimorphSharing.
PolimorphSharing is simply and an abstract class that implements the methods I want public from Service 1 and Service 2. Those methods will then be overridden on the Service 1 and Service 2.
Because I need a way to switch the service in runtime, I've created a gateway class that inherits from PolimorphSharing. I can then call it the following way:
private var sharingService:PolimorphSharing = new SharingServicesGW('svc1').createService();
This all works flawlessly, and I can now switch between services with no problem whatsoever. However, I feel there's something wrong about it, so I would like to ask you guys for some advice on how to better implement this.
Any opinions here would be appreciated. I feel like I'm kind of implementing the factory pattern here the hard way.
UPDATE:
Just adding some more insight to this. Basically the idea here is for my client to be able to upload images with various different public sharing services such as imageshack, imgur etc. I want my client to be able to select the service in which the image is to be published to (hence the "switching between them with user interaction" bit of the question.
The method that does the uploading bit, is requestShareImage(), processResults() simply turns whatever gets returned to a unique format, so my client can read off it always the same way. getObject() is my accessor, and onIOError will handle exceptions with any of the public API's
Thanks all in advance,
SharingServicesGW IS a factory. However, there's no need for it to - and it shouldn't - inherit from PolimorphSharing. Also you're doing it a bit skewed. The client should be using objects of the interface type, not the abstract type.
Your interface should be defining the public API, not your abstract base class. In fact in AS3 interfaces can only define public members, while pseudo abstract classes can enforce implementation of protected members.
-- EDIT --
here's a UML diagram of how I would do it

AS3 How do you access an instance of a class from anywhere?

I currently pass a reference to my model through the constructor to any class that needs it in my simple mvc pattern, this can get annoying at times when it starts to go deeper.
How do Classes such as LoadMax allow you from anywhere to simple import the class, and do something like addChild(LoaderMax.getContent("bg"));? Replicating this should surely be a good way to have my model work, without the complexity of big frameworks?
Statics are your friend
As previous answers have noted, TweenLite/Max etc. makes heavy use of static members to get work done. This is exactly like the Math class, for example, and can be a very convenient design pattern. You have global access to the class, and that can definitely alleviate the issue of getting access to variables through deeply nested classes.
Statics are the enemy
Statics, however, bring certain problems to the table. Most importantly, they tend to reduce flexibility and modularity of classes through the often unnecessary addition of tightly coupled relationships. It's a bit like pouring concrete over your application. It does work, but changing behavior becomes difficult as project features change.
Static members != instance members
Note, very clearly, that a static member "belongs" to the class itself, and not an instance of that class. Static members have no access to instance members. This causes troubles when you want to mix these members up in logic. You tend to have to make everything static (the so-called "static-cling" effect). Static patterns are often argued to be argued to be "anti" object-oriented, for precisely this reason. Once you build a structure on a static pattern you tend to lose many of the principles that makes OOD powerful.
In small does, they're pretty nice
That all being said - TweenLite is a great example of a static pattern that is totally appropriate - its a utility package, one that logic is not dependent on. And that should probably be how you leverage statics, too.
To reduce reliance on statics, or even global vars, it does often mean writing more code, but the flexibility in app structure gained is often quite worth it. #Marty_Wallace has a pretty good solution imo.
Demeter and the Paperboy
Finally, I'll just mention the Law of Demeter, or the Principle of Least Knowledge, and the related Paperboy and the Wallet example, which is often pointed to in discussions of statics:
Each unit should have only limited knowledge about other units: only
units "closely" related to the current
unit.
Each unit should only talk to its friends; don't talk to strangers.
Only talk to your immediate friends.
Hopefully that sheds a little bit of light on a fairly complicated and not-often obvious issue.
This is done using the static namespace, however I discourage the use of this.
package
{
public class Main
{
public static function sayHell():void
{
trace("hello!");
}
}
}
You can now call sayHello() like this from anywhere in the application (assuming you've imported the class).
Main.sayHello();
Another thing you can do (to make the entire class accessible from within the application) is create a static property that refers to the class itself:
package
{
public class Something
{
public static var instance:Something;
public function Something()
{
instance = this;
}
public function someFunction():void
{
trace('hello!');
}
}
}
Which you can now use like so:
Something.instance.someFunction();
The only thing to note here is that you need to create an instance of Something for this to work to call the constructor and define instance.
What I would do
Create a base class for all objects in your application
Create a manager class that takes care of these objects
Create a setter within your base class to define the manager
Here's an example:
Base
package
{
public class Base extends Object
{
private var _manager:Manager;
public function set manager(m:Manager):void
{
_manager = m;
init();
}
protected function init():void
{
manager.someFunction();
}
public function get manager():Manager{ return _manager; }
}
}
Manager
package
{
public class Manager extends Object
{
public function someFunction():void
{
trace('hello!');
}
}
}
Now anything that extends Base will have access to anything held in Manager via the manager getter property. All you need to do is make sure you define the manager, which is easily achieved from within anything that extends Base like so:
var something:SomeExtendingClass = new SomeExtendingClass();
something.manager = manager;
The example you gave is just a static method, but to answer your question about a global instance of a class:
package myPackage
{
public var globalVariable:MyClass = new MyClass();
}
You can access it with:
import myPackage.globalVariable;
trace(globalVariable);
I think you have to rethink in which way you want to name your classes.
You can instantiate whatever class you want, at run-time, but to access a instance by name, you have to make changes in your structure. For example, the getContent() function you mentioned in LoaderMax, all it does is to search in an array for the given loader that matchs the name, among other things. You can read the name variable comment for a description.
A name that you use to identify the loader instance. This name can be fed to the getLoader() or getContent() methods or traced at any time. Each loader's name should be unique. If you don't define one, a unique name will be created automatically, like "loader21".
So in this system, you have to name every single member (loaders in this case) if you want to be able to search them. Because if I call getClassInstance("myinstance"), what is "myinstance" representing? Where should I name it?
That said, if you want to do it for DisplayObjects only, you can use getChildByName. But again, you have to name every DisplayObject (just set the name variable).
Hope this helps.

How do you create your Factories?

So, coming upon the subject of Factories, I'm wondering how they are set up.
From where I stand, I can see 3 types of Factories:
All In One
A factory that basically contains all of the classes used in an application. It feels like it is just having a factory for the sake of having a factory, and doesn't really feel structured.
Example (Where ClassA, Class B, and ClassC have nothing in common except being in the same App):
class Factory
{
public static function buildClassA()
public static function buildClassB()
public static function buildClassC()
}
Code samples provided are in PHP. However, this question is language-agnostic.
Built-In Factory
The next one is mixing in static functions with the regular functions in order to make special creation patterns (see this question)
Example:
class ClassA
{
public static function buildClass()
public function __construct()
}
Factory On-the-Side
The last one I can think of is having a factory for individual classes, or individual sets of classes. This just seems to variable to be used in an uniform manner.
Example (Where ClassA, B, and C are related, and 1, 2, and 3 are related):
class FactoryAlpha
{
public static function buildClassA()
public static function buildClassB()
public static function buildClassC()
}
class FactoryNumeric
{
public static function buildClass1()
public static function buildClass2()
public static function buildClass3()
}
My question is: Are all of these bad ideas, are any of them bad ideas? Are there other ways of creating factories? Are any of these actually good ideas? What is a good/best way to create Factories.
The point of a factory seems to be to have the code that uses it not need to know which concrete class will be constructed (this should be handled by configuring the factory). That seems to rule out "All-in One" and "Factory-on-the-Side".
I like the approach that Java libraries often use: You have a static method that creates the Factory. The Factory has a getInstance method that creates the instance. This gives you two points of configuration (via system properties): The default FactoryImpl has a number of settings, such as the class it should produce, and if these configuration options are not enough, you can also swap out the FactoryImpl altogether.
As for "All-in One" vs "Factory-on-the-Side", a Factory should not produce unrelated classes I think. Again, it Java terms, every factory produces instances of a certain interface.
"All-in-One" sounds like something that should be replaced with Dependency Injection (where you have a container that produces all kinds of instances and injects them into the application).
If you are really interested in "Preferred technologies", I'd replace them all with Dependency Injection.
If that seems to heavy, just remember that you may not be seeing every use for your factory so don't "New" a hard-coded class in your factory. Instead, have a "Setter" that can specify what class needs to be injected.
This will come in handy later when you are unit testing and need to start injecting mock classes.
But as you make this more general, abstract and reusable, you'll end up back at DI. (Just don't say I didn't warn you)
There's really just two standard sorts of factories, at least according to GOF and the slew of patterns books that followed: The basic Factory, and the Abstract Factory.
A Factory generally returns a concrete instance that the caller refers to through an interface, like so:
// createWidget() here instantiates a BigWidget or SmallWidget or whatever the context calls for
IWidget widget = WidgetFactory.createWidget(someContextValue);
Using a factory with an interface in this way keeps the caller from being coupled into a specific type of the returned object. Following the venerable Single Responsibility Principle, a factory should do one thing, that is, return a concrete instance of the interface that was called for, and nothing more. A basic factory should only have the job of creating one type of object.
An Abstract Factory, on the other hand, can be thought of as a factory of factories, and might be closer to what you were thinking of as an "all in one" factory. An Abstract Factory is usually configured at start-up to return a group of related factories, for instance factories that might create a particular family of GUIs depending on a given context. This is an example of Dependency Inversion that has largely been replaced by using IOC containers like Spring.

Registering derived classes with reflection, good or evil?

As we all know, when we derive a class and use polymorphism, someone, somewhere needs to know what class to instanciate. We can use factories, a big switch statement, if-else-if, etc. I just learnt from Bill K this is called Dependency Injection.
My Question: Is it good practice to use reflection and attributes as the dependency injection mechanism? That way, the list gets populated dynamically as we add new types.
Here is an example. Please no comment about how loading images can be done other ways, we know.
Suppose we have the following IImageFileFormat interface:
public interface IImageFileFormat
{
string[] SupportedFormats { get; };
Image Load(string fileName);
void Save(Image image, string fileName);
}
Different classes will implement this interface:
[FileFormat]
public class BmpFileFormat : IImageFileFormat { ... }
[FileFormat]
public class JpegFileFormat : IImageFileFormat { ... }
When a file needs to be loaded or saved, a manager needs to iterate through all known loader and call the Load()/Save() from the appropriate instance depending on their SupportedExtensions.
class ImageLoader
{
public Image Load(string fileName)
{
return FindFormat(fileName).Load(fileName);
}
public void Save(Image image, string fileName)
{
FindFormat(fileName).Save(image, fileName);
}
IImageFileFormat FindFormat(string fileName)
{
string extension = Path.GetExtension(fileName);
return formats.First(f => f.SupportedExtensions.Contains(extension));
}
private List<IImageFileFormat> formats;
}
I guess the important point here is whether the list of available loader (formats) should be populated by hand or using reflection.
By hand:
public ImageLoader()
{
formats = new List<IImageFileFormat>();
formats.Add(new BmpFileFormat());
formats.Add(new JpegFileFormat());
}
By reflection:
public ImageLoader()
{
formats = new List<IImageFileFormat>();
foreach(Type type in Assembly.GetExecutingAssembly().GetTypes())
{
if(type.GetCustomAttributes(typeof(FileFormatAttribute), false).Length > 0)
{
formats.Add(Activator.CreateInstance(type))
}
}
}
I sometimes use the later and it never occured to me that it could be a very bad idea. Yes, adding new classes is easy, but the mechanic registering those same classes is harder to grasp and therefore maintain than a simple coded-by-hand list.
Please discuss.
My personal preference is neither - when there is a mapping of classes to some arbitrary string, a configuration file is the place to do it IMHO. This way, you never need to modify the code - especially if you use a dynamic loading mechanism to add new dynamic libraries.
In general, I always prefer some method that allows me to write code once as much as possible - both your methods require altering already-written/built/deployed code (since your reflection route makes no provision for adding file format loaders in new DLLs).
Edit by Coincoin:
Reflection approach could be effectively combined with configuration files to locate the implmentations to be injected.
The type could be declared explicitely in the config file using canonical names, similar to MSBuild <UsingTask>
The config could locate the assemblies, but then we have to inject all matching types, ala Microsoft Visual Studio Packages.
Any other mechanism to match a value or set of condition to the needed type.
My vote is that the reflection method is nicer. With that method, adding a new file format only modifies one part of the code - the place where you define the class to handle the file format. Without reflection, you'll have to remember to modify the other class, the ImageLoader, as well
Isn't this pretty much what the Dependency Injection pattern is all about?
If you can isolate the dependencies then the mechanics will almost certainly be reflection based, but it will be configuration file driven so the messiness of the reflection can be pretty well encapsulated and isolated.
I believe with DI you simply say I need an object of type <interface> with some other parameters, and the DI system returns an object to you that satisfies your conditions.
This goes together with IoC (Inversion of Control) where the object being supplied may need something else, so that other thing is automatically created and installed into your object (being created by DI) before it's returned to the user.
I know this borders on the "no comment about loading images other ways", but why not just flip your dependencies -- rather than have ImageLoader depend on ImageFileFormats, have each IImageFileFormat depend on an ImageLoader? You'll gain a few things out of this:
Each time you add a new IImageFileFormat, you won't need to make any changes anywhere else (and you won't have to use reflection, either)
If you take it one step further and abstract ImageLoader, you can mock it in Unit Tests, making testing the concrete implementations of each IImageFileFormat that much easier
In vb.net, if all the image loaders will be in the same assembly, one could use partial classes and events to achieve the desired effect (have a class whose purpose is to fire an event when the image loaders should register themselves; each file containing image loaders can have use a "partial class" to add another event handler to that class); C# doesn't have a direct equivalent to vb.net's WithEvents syntax, but I suspect partial classes are a limited mechanism for achieving the same thing.

Fluent Interfaces - Method Chaining

Method chaining is the only way I know to build fluent interfaces.
Here's an example in C#:
John john = new JohnBuilder()
.AddSmartCode("c#")
.WithfluentInterface("Please")
.ButHow("Dunno");
Assert.IsNotNull(john);
[Test]
public void Should_Assign_Due_Date_With_7DayTermsVia_Invoice_Builder()
{
DateTime now = DateTime.Now;
IInvoice invoice = new InvoiceBuilder()
.IssuedOn(now)
.WithInvoiceNumber(40)
.WithPaymentTerms(PaymentTerms.SevenDays)
.Generate();
Assert.IsTrue(invoice.DateDue == now.AddDays(7));
}
So how do others create fluent interfaces. How do you create it? What language/platform/technology is needed?
The core idea behind building a fluent interface is one of readability - someone reading the code should be able to understand what is being achieved without having to dig into the implementation to clarify details.
In modern OO languages such as C#, VB.NET and Java, method chaining is one way that this is achieved, but it's not the only technique - two others are factory classes and named parameters.
Note also that these techniques are not mutually exclusive - the goal is to maximize readabilty of the code, not purity of approach.
Method Chaining
The key insight behind method chaining is to never have a method that returns void, but to always return some object, or more often, some interface, that allows for further calls to be made.
You don't need to necessarily return the same object on which the method was called - that is, you don't always need to "return this;".
One useful design technique is to create an inner class - I always suffix these with "Expression" - that exposes the fluent API, allowing for configuration of another class.
This has two advantages - it keeps the fluent API in one place, isolated from the main functionality of the class, and (because it's an inner class) it can tinker with the innards of the main class in ways that other classes cannot.
You may want to use a series of interfaces, to control which methods are available to the developer at a given point in time.
Factory Classes
Sometimes you want to build up a series of related objects - examples include the NHibernate Criteria API, Rhino.Mocks expectation constraints and NUnit 2.4's new syntax.
In both of these cases, you have the actual objects you are storing, but to make them easier to create there are factory classes providing static methods to manufacture the instances you require.
For example, in NUnit 2.4 you can write:
Assert.That( result, Is.EqualTo(4));
The "Is" class is a static class full of factory methods that create constraints for evaluation by NUnit.
In fact, to allow for rounding errors and other imprecision of floating point numbers, you can specify a precision for the test:
Assert.That( result, Is.EqualTo(4.0).Within(0.01));
(Advance apologies - my syntax may be off.)
Named Parameters
In languages that support them (including Smalltalk, and C# 4.0) named parameters provide a way to include additional "syntax" in a method call, improving readability.
Consider a hypothetical Save() method that takes a file name, and permissions to apply to the file after saving:
myDocument.Save("sampleFile.txt", FilePermissions.ReadOnly);
with named parameters, this method could look like this:
myDocument.Save(file:"SampleFile.txt", permissions:FilePermissions.ReadOnly);
or, more fluently:
myDocument.Save(toFile:"SampleFile.txt", withPermissions:FilePermissions.ReadOnly);
You can create a fluent interface in any version of .NET or any other language that is Object Oriented. All you need to do is create an object whose methods always return the object itself.
For example in C#:
public class JohnBuilder
{
public JohnBuilder AddSmartCode(string s)
{
// do something
return this;
}
public JohnBuilder WithfluentInterface(string s)
{
// do something
return this;
}
public JohnBuilder ButHow(string s)
{
// do something
return this;
}
}
Usage:
John = new JohnBuilder()
.AddSmartCode("c#")
.WithfluentInterface("Please")
.ButHow("Dunno");
AFAIK, the term fluent interface does not specify a specific technology or framework, but rather a design pattern. Wikipedia does have an extensive example of fluent interfaces in C♯.
In a simple setter method, you do not return void but this. That way, you can chain all of the statements on that object which behave like that. Here is a quick example based on your original question:
public class JohnBuilder
{
private IList<string> languages = new List<string>();
private IList<string> fluentInterfaces = new List<string>();
private string butHow = string.Empty;
public JohnBuilder AddSmartCode(string language)
{
this.languages.Add(language);
return this;
}
public JohnBuilder WithFluentInterface(string fluentInterface)
{
this.fluentInterfaces.Add(fluentInterface);
return this;
}
public JohnBuilder ButHow(string butHow)
{
this.butHow = butHow;
return this;
}
}
public static class MyProgram
{
public static void Main(string[] args)
{
JohnBuilder johnBuilder = new JohnBuilder().AddSmartCode("c#").WithFluentInterface("Please").ButHow("Dunno");
}
}
Sometime ago I had the same doubts you are having now. I've done some research and now I'm writing a series of blog posts about techinics of designing a fluent interface.
Check it out at:
Guidelines to Fluent Interface design in C# part 1
I have a section there about Chaining X Nesting that can be interesting to you.
In the following posts I will talk about it in a deeper way.
Best regards,
André Vianna
Fluent interface is achieved in object oriented programming by always returning from your methods the same interface that contains the method. Consequently you can achieve this effect in java, javascript and your other favorite object oriented languages, regardless of version.
I have found this technique easiest to accomplish through the use of interfaces:
public interface IFoo
{
IFoo SetBar(string s);
IFoo DoStuff();
IFoo SetColor(Color c);
}
In this way, any concrete class that implements the interface, gets the fluent method chaining capabilities. FWIW.. I wrote the above code in C# 1.1
You will find this technique littered throughout the jQuery API
A couple of things come to mind that are possible in .Net 3.5/C# 3.0:
If an object doesn't implement a fluent interface, you could use Extension Methods to chain your calls.
You might be able to use the object initialization to simulate fluent, but this only works at instantiation time and would only work for single argument methods (where the property is only a setter). This seems hackish to me, but the there it is.
Personally, I don't see anything wrong with using function chaining if you are implementing a builder object. If the builder object has chaining methods, it keeps the object you are creating clean. Just a thought.
This is how I've built my so called fluent interfaces or my only forary into it
Tokenizer<Bid> tkn = new Tokenizer<Bid>();
tkn.Add(Token.LambdaToken<Bid>("<YourFullName>", b => Util.CurrentUser.FullName))
.Add(Token.LambdaToken<Bid>("<WalkthroughDate>",
b => b.WalkThroughDate.ToShortDateString()))
.Add(Token.LambdaToken<Bid>("<ContactFullName>", b => b.Contact.FullName))
.Cache("Bid")
.SetPattern(#"<\w+>");
My example required .net 3.5 but that's only cause of my lambda's. As Brad pointed out you can do this in any version of .net. Although I think lambda's make for more interesting possibilities such as this.
======
Some other good examples are nHibernate's Criteria API, there is also a fluent nhibernate extension for configuring nhibernate but I've never used it
Dynamic keyword in C# 4.0 will make it possible to write dynamic style builders. Take a look at following article about JSON object construction.