I'm trying to design a interface for iTextsharp (PDF creation library) that I'm using for my project. I don't want any reference to iTextsharp in my project, just the interface.
Lets say, I have
interface IPdfTable { /* */ }
public class PdfTable : IPdfTable { /* */ }
interface IPdfCell { /* */ }
public class PdfCell : PdfCell { /* */ }
While I can easily build interfaces for each class individualy, I'm having difficulty on the implementation when these classes interact with each other. Somewhere in the code, I need tables to be able to accept an collection of cells.
The problem arrives when I have a have an collection of cells, and I need to add it to the table. Somehow I need to transform the IPdfCell into the original element that is accepted by the library (iTextSharp). I believe the quick and easy implementation was downcasting, but not a good design.
The only other solution I can think is using the interface to collection varies settings and create the orginal element (accepted by iTextsharp) on the fly when it is being passed around into other elements.
Is there a better implementation?
I don't understand the goal of such an interface. No matter what, your pdf generation code is going to be tied to the library you're using, building proxy classes/interfaces that exactly mirror the library doesn't prevent that, it just adds another layer. If you were to switch to a different PDF generation library, it is extremely unlikely that the new library would match up 1:1 with equivalents in iText, and you'd end up changing the interface and calling code anyway.
My recommendation would be to create an IPDFGenerator, and then create an iTextPDFGenerator:IPDFGenerator which IS coupled to iText, and leave it at that. You'll have the separation you want, the ability to keep iText out of your core services, but it won't require a bunch of pointless mapping between identical classes.
I think you should reevaluate the S, I, and D in SOLID and make sure you're not over-doing it.
Typically, you would have a translation layer that translates your interface facade implementation into the types supported natively by iTextSharp.
AutoMapper can help for this if you require property to property mappings and can remove a lot of the translation legwork for you.
Related
I'm reading a book which shows an example below:
Assume you are developing a collection of geometric classes named Square,
Circle, and Hexagon. Given their similarities, you would like to group them together into a unique namespace called MyShapes within the CustomNamespaces.exe assembly. You have two basic approaches. First, you can choose to define all classes in a single C# file (ShapesLib.cs) as follows:
// ShapesLib.cs
using System;
namespace MyShapes
{
public class Circle { /* Interesting members... */ }
public class Hexagon { /* More interesting members... */ }
public class Square { /* Even more interesting members... */ }
}
While the C# compiler has no problems with a single C# code file containing multiple types, this could be cumbersome when you want to reuse class definitions in new projects. For example, say you are building a new project and only need to use the Circle class. If all types are defined in a single code file, you are more or less stuck with the entire set. Therefore, as an alternative, you can split a single namespace across multiple C# files.
// Circle.cs
using System;
namespace MyShapes
{
public class Circle { /* Interesting methods... */ }
}
// Hexagon.cs
using System;
namespace MyShapes
{
public class Hexagon { /* More interesting methods... */ }
}
// Square.cs
using System;
namespace MyShapes
{
public class Square { /* Even more interesting methods... */ }
}
I don't quite understand it, what does reuse class definitions in new projects mean? In both case, when you want to use Circle class in other projects, you need to use MyShapes.Circle c = new Circle() explicitly or use using MyShapes; Circle c = new Circle();, so there is really no difference between "define all classes in a single C# file' or "split a single namespace across multiple C# files"?
"you are more or less stuck with the entire set. Therefore, as an
alternative, you can split a single namespace across multiple"
The wording is suspect, and your intuitions are correct, you are still suck with the entire set. They are the same thing, the only difference is you have class per file that share the same namespace (which some might say) can be easier to maintain in several ways such as readability, git commits and merges etc.
In any normal sense and directly relating to the authors comment "you are more or less stuck with the entire set", this would only start to make a substantial difference when you had each shape in a different project / Nuget and you could selectively and granularly reference each shape, with the advantage that all shapes are still under the same archetype namespace. Even then, shapes are not the best analogy.
Without getting bogged down in the semantics of the wording, the author is just implying you can split individual classes across files and have them still reside in the same namespace.
cumbersome when you want to reuse class definitions in new projects
Basically, it is exactly what is written. If you have namespace for a project that contains a number of classes, if in the future you would like to reuse a class (why reinvent the wheel when you have already done the leg work - common in the professional setting), you would have to import the classes that you need.
But, if you have only one class that you needs to be imported (i.e. included in your project), but that class is in a file representing a number of classes - you will be importing all of the additional classes even though the project you are going to be working on has no need for them. It is wasted memory.
In addition, and this is not something that has been mentioned, it is a good practice to separate classes into their own files for easier readability and code management in the future. Especially if your classes will grow to represent large objects that will have many methods, properties, etc. You would not want to have a 1000+ line file.
There are various good reasons for having one class = one file.
you can copy the single .cs file in another project and with a little luck it will just work, and you won't import useless things (I say little luck because often a class uses other classes... For example all the shapes could have a class Shape as a base class... Then to copy Circle to another project you would have to copy both Circle and Shape)
it is easy to find the .cs file that contains a class: it has the same name as the class. If a file contains multiple classes, what name should the file have? It is quite easy after some time to have the filename become "obsolete" because you added some more classes
it is quite easy to make a class that is already too much big as the number of lines... If you begin putting multiple classes in the same file this problem will only increase. But normally you don't have to check all the classes together... Perhaps today you have to work on Circle and tomorrow on Square. It is quite useless to have both of them at the same time. It would be like always carring around useless tools.
if you work with a VCS (Version Control System), like github, it is easy to see what files have been modified. If one file = one class, you can have an idea about what has been modified. If multiple classes are inside a single file, everything becomes murkier
There are surely other good reasons... But the main good reason is: everyone is doing it... So probably it is the correct way. In at least a language (Java), it isn't a suggestion, it is a rule. One file = one public class.
I have a database that contains "widgets", let's say. Widgets have properties like Length and Width, for example. The original lower-level API for creating wdigets is a mess, so I'm writing a higher-level set of functions to make things easier for callers. The database is strange, and I don't have good control over the timing of the creation of a widget object. Specifically, it can't be created until the later stages of processing, after certain other things have happened first. But I'd like my callers to think that a widget object has been created at an earlier stage, so that they can get/set its properties from the outset.
So, I implemented a "ProxyWidget" object that my callers can play with. It has private fields like private_Length and private_Width that can store the desired values. Then, it also has public properties Length and Width, that my callers can access. If the caller tells me to set the value of the Width property, the logic is:
If the corresponding widget object already exists in the database, then set
its Width property
If not, store the given width value in the private_Width field for later use.
At some later stage, when I'm sure that the widget object has been created in the database, I copy all the values: copy from private_Width to the database Width field, and so on (one field/property at a time, unfortunately).
This works OK for one type of widget. But I have about 50 types, each with about 20 different fields/properties, and this leads to an unmaintainable mess. I'm wondering if there is a smarter approach. Perhaps I could use reflection to create the "proxy" objects and copy field/property data in a generic way, rather than writing reams of repetitive code? Factor out common code somehow? Can I learn anything from "data binding" patterns? I'm a mathematician, not a programmer, and I have an uneasy feeling that my current approach is just plain dumb. My code is in C#.
First, in my experience, manually coding a data access layer can feel like a lot of repetitive work (putting an ORM in place, such as NHibernate or Entity Framework, might somewhat alleviate this issue), and updating a legacy data access layer is awful work, especially when it consists of many parts.
Some things are unclear in your question, but I suppose it is still possible to give a high-level answer. These are meant to give you some ideas:
You can build ProxyWidget either as an alternative implementation for Widget (or whatever the widget class from the existing low-level API is called), or you can implement it "on top of", or as a "wrapper around", Widget. This is the Adapter design pattern.
public sealed class ExistingTerribleWidget { … }
public sealed class ShinyWidget // this is the wrapper that sits on top of the above
{
public ShinyWidget(ExistingTerribleWidget underlying) { … }
private ExistingTerribleWidget underlying;
… // perform all real work by delegating to `underlying` as appropriate
}
I would recommend that (at least while there is still code using the existing low-level API) you use this pattern instead of creating a completely separate Widget implementation, because if ever there is a database schema change, you will have to update two different APIs. If you build your new EasyWidget class as a wrapper on top of the existing API, it could remain unchanged and only the underlying implementation would have to be updated.
You describe ProxyWidget having two functions (1) Allow modifications to an already persisted widget; and (2) Buffer for a new widget, which will be added to the database later.
You could perhaps simplify your design if you have one common base type and two sub-classes: One for new widgets that haven't been persisted yet, and one for already persisted widgets. The latter subtype possibly has an additional database ID property so that the existing widget can be identified, loaded, modified, and updated in the database:
interface IWidget { /* define all the properties required for a widget */ }
interface IWidgetTemplate : IWidget
{
IPersistedWidget Create();
bool TryLoadFrom(IWidgetRepository repository, out IPersistedWidget matching);
}
interface IPersistedWidget : IWidget
{
Guid Id { get; }
void SaveChanges();
}
This is one example for the Builder design pattern.
If you need to write similar code for many classes (for example, your 50+ database object types) you could consider using T4 text templates. This just makes writing code less repetitive; but you will still have to define your 50+ objects somewhere.
How would you design an application (classes, interfaces in class library) in .NET when we have a fixed database design on our side and we need to support imports of data from third party data sources, which will most likely be in XML?
For instance, let us say we have a Products table in our DB which has columns
Id
Title
Description
TaxLevel
Price
and on the other side we have for instance Products:
ProductId
ProdTitle
Text
BasicPrice
Quantity.
Currently I do it like this:
Have the third party XML convert to classes and XSD's and then deserialize its contents into strong typed objects (what we get as a result of this process is classes like ThirdPartyProduct, ThirdPartyClassification, etc.).
Then I have methods like this:
InsertProduct(ThirdPartyProduct newproduct)
I do not use interfaces at the moment but I would like to. What I would like is implement something like
public class Contoso_ProductSynchronization : ProductSynchronization
{
public void InsertProduct(ContosoProduct p)
{
Product product = new Product(); // this is our Entity class
// do the assignments from p to product here
using(SyncEntities db = new SyncEntities())
{
// ....
db.AddToProducts(product);
}
}
// the problem is Product and ContosoProduct have no arhitectural connection right now
// so I cannot do this
public void InsertProduct(ContosoProduct p)
{
Product product = (Product)p;
using(SyncEntities db = new SyncEntities())
{
// ....
db.AddToProducts(product);
}
}
}
where ProductSynchronization will be an interface or abstract class. There will most likely be many implementations of ProductSynchronization. I cannot hardcode the types - classes like ContosoProduct, NorthwindProduct might be created from the third party XML's (so preferably I would continue to use deserialization).
Hopefully someone will understand what I'm trying to explain here. Just imagine you are the seller and you have numerous providers and each one uses their own proprietary XML format. I don't mind the development, which will of course be needed everytime new format appears, because it will only require 10-20 methods to be implemented, I just want the architecture to be open and support that.
In your replies, please focus on design and not so much on data access technologies because most are pretty straightforward to use (if you need to know, EF will be used for interacting with our database).
[EDIT: Design note]
Ok, from a design perspective I would do xslt on the incoming xml to transform it to a unified format. Also very easy to verify the result xml towards a schema.
Using xslt I would stay away from any interface or abstract class, and just have one class implementation in my code, the internal class. It would keep the code base clean, and the xslt's themselves should be pretty short if the data is as simple as you state.
Documenting the transformations can easily be done wherever you have your project documentation.
If you decide you absolutely want to have one class per xml (or if you perhaps got a .net dll instead of xml from one customer), then I would make the proxy class inherit an interface or abstract class (based off your internal class, and implement the mappings per property as needed in the proxy classes. This way you can cast any class to your base/internal class.
But seems to me doing the conversion/mapping in code will make the code design a bit more messy.
[Original Answer]
If I understand you correctly you want to map a ThirdPartyProduct class over to your own internal class.
Initially I am thinking class mapping. Use something like Automapper and configure up the mappings as you create your xml deserializing proxy's. If you make your deserialization end up with the same property names as your internal class, then there's less config to do for the mapper. Convention over Configuration.
I'd like to hear anyones thoughts on going this route.
Another approach would be to add a .ToInternalProduct( ThirdPartyClass ) in a Converter class. And keep adding more as you add more external classes.
The third approach is for XSLT guys. If you love XSLT you could transform the xml into something which can be deserialized into your internal product class.
Which one of these three I'd choose would depend on the skills of the programmer, and who will maintain adding new external classes. The XSLT approach would require no recompiling or compiling of code as new formats arrived. That might be an advantage.
I strongly believe that, reading code and reading good code is key to great programming. If not one of the many.
I had been facing some problems in visualizing and having a "feel" of using inheritance to better my code architecture.
Can somebody give me some link to good code to emulate, where folks have used inheritance in an absolute "kung-fooey ruthless" manner [in a good way]
I strongly believe that, reading code and reading good code is key to great programming
Hard to disagree.
Actually the qestion is pretty hard - becouse there is some alternatives to inheritance, such as composite reuse principle, so sometimes it's very hard to diside if inheritance is used in "kung-fooey ruthless" manner or there ware some better way to implement the same wich will make code esier to understand/test/make it lossely coupled and so on.
In my humble opinion Enterprise Library Application validation block whith it's Microsoft.Practices.EnterpriseLibrary.Validation.Validator class with all it's descendants
is a very good example of inheritance, becouse
concept of validation is easy to understand
there is good example how to find common in objects of with pretty different nature (i.e. OrCompositeValidator/DateTimeRangeValidator/ObjectCollectionValidator)
many of us tried to implement something more or less like this, so this background will give more quality for understanding
this is clear(for me, but I can be wrong:) that inheritance has no alternatives there
You can download source code from codeplex.
An example of good usage of inheritance would be the .NET framework classes. You can download the MONO project to gain access to some source code. If you want to better your code architecture, invest some time in studying architectural design patterns.
Here is a personal example where I've made use of inheritance to greatly benefit a development situation:
I needed to develop a asp.net (c#) form control set, which would allow both standard web forms (bunch of form fields with submit button), as well as a secure version which talks to a web service to submit the information over SSL.
Because of all of the similarities between the controls and concepts, I developed a number of classes:
BaseWebControl
custom base control class that inherits from System.Web.UI.WebControl class (part of .NET framework
has custom properties and methods that are used in our application by all custom controls (control state info, etc.)
BaseFormControl
inherits from BaseWebControl, gaining all of its underlying functionality
handles base form functionality, such as dynamically adding fieldsets, marking required fields, adding submit button, etc. etc.
contains a label and associated control index for easy lookups
marked as an abstract class, with abstract method called SubmitForm. This method is not defined on this class, however it is called by the submit button click event. This means that any specific form control class that inherits from this base class can implement the abstract SubmitForm functionality as needed.
EmailFormControl
Inherits from BaseFormControl, so it gains all underlying functionality above without any duplication
contains very little, except overrides the abstract method SubmitForm, and generates an email based on the form fields.
all other control functionality and event handling is dealt with by the base class. In the base class when the submit button is clicked and handled, it calls this specific implementation of SubmitForm
SecureFormControl
Again inherits from BaseFormControl, so it gains all underlying functionality above without any duplication
In its implementation of SubmitForm, it connects to a WCF web service and passes the information in over SSL.
no other functionality is required because base class handles the rest.
In stripped down code form, the general outline is as such:
public class BaseWebControl : System.Web.UI.WebControl
{
//base web control with application wide functionality built in
}
public abstract class BaseFormControl : BaseWebControl
{
//handles all 'common' form functionality
//...
//...
//event handler for submit button calls abstract method submit form,
//which must be implemented by each inheriting class
protected void btnSubmit_Click(object sender, EventArgs e)
{
SubmitForm();
}
protected abstract SubmitForm();
}
public class EmailFormControl : BaseFormControl
{
protected override SubmitForm()
{
//implement specific functionality to email form contents
}
}
public class SecureFormControl : BaseFormControl
{
protected override SubmitForm()
{
//connect to WCF web service and submit contents
}
}
As a result of the above, BaseFormControl has about 1000 lines of code in a whole bunch of methods, properties, etc. SecureFormControl and EmailFormControl each have about 40 lines. All other functionality is shared and controlled by the base class. This promotes:
maintainability
efficiency
flexibility
consistency
Now I can create any type of web form, such as DataBaseFormControl, etc. etc. very easily. I can add great new functionality to all forms by adding methods and properties to the base classes, etc.
And the list goes on.
Phew that was a lot of typing. Hope this helps give you a good example. This was one instance where I found inheritance to be a key success point in a project.
I agree with the recommendation to look at the .NET base class library, as it has excellent examples of abstraction via both inheritance and interfaces. The goal is to insulate consumer code from having to care about the details of a particular implementation. The WinForms designer works with Controls, but it has no idea what specific kinds of Controls will be implemented. It doesn't care, because inheritance abstracts away the unnecessary details. LINQ works similarly with IEnumerable; it doesn't really matter what's being enumerated, as there are algorithms you can write that work with anything enumerable. Both are excellent examples of abstraction used well.
How does one go about create an API that is fluent in nature?
Is this using extension methods primarily?
This article explains it much better than I ever could.
EDIT, can't squeeze this in a comment...
There are two sides to interfaces, the implementation and the usage. There's more work to be done on the creation side, I agree with that, however the main benefits can be found on the usage side of things. Indeed, for me the main advantage of fluent interfaces is a more natural, easier to remember and use and why not, more aesthetically pleasing API. And just maybe, the effort of having to squeeze an API in a fluent form may lead to better thought out API?
As Martin Fowler says in the original article about fluent interfaces:
Probably the most important thing to
notice about this style is that the
intent is to do something along the
lines of an internal
DomainSpecificLanguage. Indeed this is
why we chose the term 'fluent' to
describe it, in many ways the two
terms are synonyms. The API is
primarily designed to be readable and
to flow. The price of this fluency is
more effort, both in thinking and in
the API construction itself. The
simple API of constructor, setter, and
addition methods is much easier to
write. Coming up with a nice fluent
API requires a good bit of thought.
As in most cases API's are created once and used over and over again, the extra effort may be worth it.
And verbose? I'm all for verbosity if it serves the readability of a program.
MrBlah,
Though you can write extension methods to write a fluent interface, a better approach is using the builder pattern. I'm in the same boat as you and I'm trying to figure out a few advanced features of fluent interfaces.
Below you'll see some sample code that I created in another thread
public class Coffee
{
private bool _cream;
private int _ounces;
public static Coffee Make { get { return new Coffee(); } }
public Coffee WithCream()
{
_cream = true;
return this;
}
public Coffee WithOuncesToServe(int ounces)
{
_ounces = ounces;
return this;
}
}
var myMorningCoffee = Coffee.Make.WithCream().WithOuncesToServe(16);
While many people cite Martin Fowler as being a prominent exponent in the fluent API discussion, his early design claims actually evolve around a fluent builder pattern or method chaining. Fluent APIs can be further evolved into actual internal domain-specific languages. An article that explains how a BNF notation of a grammar can be manually transformed into a "fluent API" can be seen here:
http://blog.jooq.org/2012/01/05/the-java-fluent-api-designer-crash-course/
It transforms this grammar:
Into this Java API:
// Initial interface, entry point of the DSL
interface Start {
End singleWord();
End parameterisedWord(String parameter);
Intermediate1 word1();
Intermediate2 word2();
Intermediate3 word3();
}
// Terminating interface, might also contain methods like execute();
interface End {
void end();
}
// Intermediate DSL "step" extending the interface that is returned
// by optionalWord(), to make that method "optional"
interface Intermediate1 extends End {
End optionalWord();
}
// Intermediate DSL "step" providing several choices (similar to Start)
interface Intermediate2 {
End wordChoiceA();
End wordChoiceB();
}
// Intermediate interface returning itself on word3(), in order to allow
// for repetitions. Repetitions can be ended any time because this
// interface extends End
interface Intermediate3 extends End {
Intermediate3 word3();
}
Java and C# being somewhat similar, the example certainly translates to your use-case as well. The above technique has been heavily used in jOOQ, a fluent API / internal domain-specific language modelling the SQL language in Java
This is a very old question, and this answer should probably be a comment rather than an answer, but I think it's a topic worth continuing to talk about, and this response is too long to be a comment.
The original thinking concerning "fluency" seems to have been basically about adding power and flexibility (method chaining, etc) to objects while making code a bit more self-explanatory.
For example
Company a = new Company("Calamaz Holding Corp");
Person p = new Person("Clapper", 113, 24, "Frank");
Company c = new Company(a, 'Floridex', p, 1973);
is less "fluent" than
Company c = new Company().Set
.Name("Floridex");
.Manager(
new Person().Set.FirstName("Frank").LastName("Clapper").Awards(24)
)
.YearFounded(1973)
.ParentCompany(
new Company().Set.Name("Calamaz Holding Corp")
)
;
But to me, the later is not really any more powerful or flexible or self-explanatory than
Company c = new Company(){
Name = "Floridex",
Manager = new Person(){ FirstName="Frank", LastName="Clapper", Awards=24 },
YearFounded = 1973,
ParentCompany = new Company(){ Name="Calamaz Holding Corp." }
};
..in fact I would call this last version easier to create, read and maintain than the previous, and I would say that it requires significantly less baggage behind the scenes, as well. Which to me is important, for (at least) two reasons:
1 - The cost associated with creating and maintaining layers of objects (no matter who does it) is just as real, relevant and important as the cost associated with creating and maintaining the code that consumes them.
2 - Code bloat embedded in layers of objects creates just as many (if not more) problems as code bloat in the code that consumes those objects.
Using the last version means you can add a (potentially useful) property to the Company class simply by adding one, very simple line of code.
That's not to say that I feel there's no place for method chaining. I really like being able to do things like (in JavaScript)
var _this = this;
Ajax.Call({
url: '/service/getproduct',
parameters: {productId: productId},
)
.Done(
function(product){
_this.showProduct(product);
}
)
.Fail(
function(error){
_this.presentError(error);
}
);
..where (in the hypothetical case I'm imagining) Done and Fail were additions to the original Ajax object, and were able to be added without changing any of the original Ajax object code or any of the existing code that made use of the original Ajax object, and without creating one-off things that were exceptions to the general organization of the code.
So I have definitely found value in making a subset of an object's functions return the 'this' object. In fact whenever I have a function that would otherwise return void, I consider having it return this.
But I haven't yet really found significant value in adding "fluent interfaces" (.eg "Set") to an object, although theoretically it seems like there could be a sort of namespace-like code organization that could arise out of the practice of doing that, which might be worthwhile. ("Set" might not be particularly valuable, but "Command", "Query" and "Transfer" might, if it helped organize things and facilitate and minimize the impact of additions and changes.) One of the potential benefits of such a practice, depending on how it was done, might be improvement in a coder's typical level of care and attention to protection levels - the lack of which has certainly caused great volumes grief.
KISS: Keep it simple stupid.
Fluent design is about one aesthetic design principle used throughout the API. Thou your methodology you use in your API can change slightly, but it is generally better to stay consistent.
Even though you may think 'everyone can use this API, because it uses all different types of methodology's'. The truth is the user would start feeling lost because your consistently changing the structure/data structure of the API to a new design principle or naming convention.
If you wish to change halfway through to a different design principle eg.. Converting from error codes to exception handling because some higher commanding power. It would be folly and would normally in tail lots of pain. It is better to stay the course and add functionality that your customers can use and sell than to get them to re-write and re-discover all their problems again.
Following from the above, you can see that there is more at work of writing a Fluent API than meet's the eye. There are psychological, and aesthetic choices to make before beginning to write one and even then the feeling,need, and desire to conform to customers demand's and stay consistent is the hardest of all.
What is a fluent API
Wikipedia defines them here http://en.wikipedia.org/wiki/Fluent_interface
Why Not to use a fluent interface
I would suggest not implementing a traditional fluent interface, as it increases the amount of code you need to write, complicates your code and is just adding unnecessary boilerplate.
Another option, do nothing!
Don't implement anything. Don't provide "easy" constructors for setting properties and don't provide a clever interface to help your client. Allow the client to set the properties however they normally would. In .Net C# or VB this could be as simple as using object initializers.
Car myCar = new Car { Name = "Chevrolet Corvette", Color = Color.Yellow };
So you don't need to create any clever interface in your code, and this is very readable.
If you have very complex Sets of properties which must be set, or set in a certain order, then use a separate configuration object and pass it to the class via a separate property.
CarConfig conf = new CarConfig { Color = Color.Yellow, Fabric = Fabric.Leather };
Car myCar = new Car { Config = conf };
No and yes. The basics are a good interface or interfaces for the types that you want to behave fluently. Libraries with extension methods can extend this behavior and return the interface. Extension methods give others the possibility to extend your fluent API with more methods.
A good fluent design can be hard and takes a rather long trial and error period to totally finetune the basic building blocks. Just a fluent API for configuration or setup is not that hard.
Learning building a fluent API does one by looking at existing APIs. Compare the FluentNHibernate with the fluent .NET APIs or the ICriteria fluent interfaces. Many configuration APIs are also designed "fluently".
With a fluent API:
myCar.SetColor(Color.Blue).SetName("Aston Martin");
Check out this video http://www.viddler.com/explore/dcazzulino/videos/8/
Writting a fluent API it's complicated, that's why I've written Diezel that is a Fluent API generator for Java. It generates the API with interfaces (or course) to:
control the calling flow
catch generic types (like guice one)
It generates also implementations.
It's a maven plugin.
I think the answer depends on the behaviour you want to achieve for your fluent API. For a stepwise initialization the easiest way is, in my opinion, to create a builder class that implements different interfaces used for the different steps. E.g. if you have a class Student with the properties Name, DateOfBirth and Semester the implementation of the builder could look like so:
public class CreateStudent : CreateStudent.IBornOn, CreateStudent.IInSemester
{
private readonly Student student;
private CreateStudent()
{
student = new Student();
}
public static IBornOn WithName(string name)
{
CreateStudent createStudent = new CreateStudent();
createStudent.student.Name = name;
return createStudent;
}
public IInSemester BornOn(DateOnly dateOfBirth)
{
student.DateOfBirth = dateOfBirth;
return this;
}
public Student InSemester(int semester)
{
student.Semester = semester;
return student;
}
public interface IBornOn
{
IInSemester BornOn(DateOnly dateOfBirth);
}
public interface IInSemester
{
Student InSemester(int semester);
}
}
The builder can then be used as follows:
Student student = CreateStudent.WithName("Robert")
.BornOn(new DateOnly(2002, 8, 3)).InSemester(2);
Admittedly, writing an API for more than three properties becomes tedious. For this reasons I have implemented a source generator that can do this work for you: M31.FluentAPI.