Why Does Lack of Cohesion Of Methods (LCOM) Include Getters and Setters - c#

I am looking at the LCOM metric as shown here,
http://www.ndepend.com/Metrics.aspx
So we are saying a few things,
1) A class is utterly cohesive if all its methods use all its instance fields
2) Both static and instance methods are counted, it includes also constructors, properties getters/setters, events add/remove methods
If I look at a class such as this,
public class Assessment
{
public int StartMetres { get; set; }
public int EndMetres { get; set; }
public decimal? NumericResponse { get; set; }
public string FreeResponse { get; set; }
public string Responsetype { get; set; }
public string ItemResponseDescription { get; set; }
public string StartText { get; set; }
public decimal? SummaryWeight { get; set; }
}
It gets a bad score of 0.94 because each getter and setter doesn't access 'all of the other instance fields'.
It is calculated like this,
accessAverage - methodCount / 1 - methodCount
(2 - 17) / (1 - 17) = 0.94 (rounded)
I am not understanding this metric, why should it include getters and setters? A getter and setter will always only access one single instance field.

This demonstrates that every software metric is flawed if you blindly take it to its extreme.
You know an "incohesive" class when you see one. For example:
class HedgeHog_And_AfricanCountry
{
private HedgeHog _hedgeHog;
private Nation _africanNation;
public ulong NumberOfQuills { get { return _hedgeHog.NumberOfQuills; } }
public int CountOfAntsEatenToday { get { return _hedgeHog.AntsEatenToday.Count(); } }
public decimal GrossDomesticProduct { get { return _africanNation.GDP; } }
public ulong Population { get { return _africanNation.Population; } }
}
This is obviously an incohesive class, because it contains two pieces of data that don't need to be with one another.
But while it's obvious to us that this class is incohesive, how can you get a software program to determine incohesion? How would it tell that the above class is incohesive, but this isn't?
class Customer
{
public string FullName { get; set; }
public Address PostalAddress { get; set; }
}
The metric they came up with certainly detects incohesion, but also comes up with false positives.
What if you decided this metric was important? You could create a "CustomerData" class containing just fields, and a "Customer" class that exposes the data fields as properties.
// This has no methods or getters, so gets a good cohesion value.
class CustomerData
{
public string FullName;
public Address PostalAddress;
}
// All of the getters and methods are on the same object
class Customer
{
private CustomerData _customerData;
public string FullName { get { return _customerData.FullName; } }
// etc
}
But if I'm playing this game, I can apply it to the incohesive example as well:
class Hedgehog_And_AfricanCountry_Data
{
public Hedgehog _hedgehog;
public AfricanNation _africanNation;
}
class Hedgehog_And_AfricanCountry
{
private Hedgehog_And_AfricanCountry_Data _hedgehogAndAfricanCountryData;
// etc;
}
Really, I think it's best to understand what cohesion is, and why it's a worthwhile goal, but also understand that a software tool can not properly measure it.

Related

Interface problem c#, and dependency injection

I am having a problem. Lets see an example:
you got this interface which would be implemented by Employee.cs and Owener.cs:
public interface IEmployee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Location { get; set; }
}
public class Employee: IEmployee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Location { get; set; }
}
public class Owner: IEmployee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Location { get; set; }
public string Status{ get; set; } <--- //problem string
}
Now when we are using Dependency Injection and it returns the object of employee or manager, thats where i run into problem.
public class EmployeeCheck{
private IEmployee empObj;
public EmployeeCheck(IEmployee _em)
{
empObj=_em
}
public void PrintCheck()
{
string str=_em.FirstName;
string str2=(Owner)_emp.Status <--- //problem...how do I access it?? It can't be accessed cause
//IEMployee doesn't have status field!
}
So basically if I use IEmployee as the interface , I can't access fields in new the Owner class, and if I do put them in interface, then Employee class which doesn't need to implement it, will be forced to implement something it doesn't need! And I do need IEmployee due to DI injection or other design pattern
OK, I can't use abstract class...so lets discuss more about the IStatus solution...so you are talking about writing code like this:
public interface IStatus:IEmployee
{
public string Title { get; set; }
}
public class Owner: IEmployee, IStatus
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Location { get; set; }
public string Status{ get; set; } <--- //problem string
}
But how do I work it in Employee check class?
public class EmployeeCheck
{
private IEmployee empObj;
public EmployeeCheck(IEmployee _em, IStatus)
{
empObj=_em
}
}
The scenario that you're dealing with could be handled traditionally using IoC Containers like StructureMap or Unity by using something called Named Instances. These containers provide this kind of functionality out of the box.
The same can be achieved in .NET Core in multiple ways. One way is to use the extension method from IServiceCollection. The below snippet walks you through how this could be done in your scenario
// using Microsoft.Extensions.DependencyInjection
// Startup.cs - ConfigureServices()
services.AddTransient(serviceProvider =>
{
Func<string, IMyClass> func = key =>
{
switch (key)
{
case "MyClass":
return serviceProvider.GetService<MyClass>();
case "MyClass1":
return serviceProvider.GetService<MyClass2>();
default:
throw new KeyNotFoundException();
}
};
return func;
});
//Register your services here as usual
services.AddTransient<IMyClass, MyClass>();
services.AddTransient<IMyClass, MyClass2>();
You are essentially creating a factory here that is going to give out the dependency of the type that you need based on the key. The following snippet of code shows how this can be done within your controller.
// ctor of your controller
public MyController(Func<string, IMyClass> injector)
{
// key here could be 'MyClass' or 'MyClass2'
IMyClass service = injector("<key>");
}
Below is the structure of sample classes I have considered for the above sample
// implementation 1
public class MyClass : IMyClass
{
}
// implementation 2
public class MyClass2 : IMyClass
{
}
// interface
public interface IMyClass
{
}
There are also other ways to handle this. You can take a look at this answer for other approaches.
It depends on how you use or why you have to use dependency injection. I think that in these cases according to your example it is not so good to use it, since it is giving you complexity in something simple.
If you are going to perform an action with the Status value, you could segregate the interface by generating a new one. Like this.
public interface IStatus { string Status { get; set; } } and then you implement this interface just in Owner and in your constructor EmployeeCheck you inject IStatus.
But if it is not necessary why not IEmployee you do it as an abstract class.
public abstract class Employee
{
public string Name { get; set; }
public string LastName { get; set; }
public string Location { get; set; }
}
public class Owner : Employee
{
public string Status { get; set; }
}
public class EmployeeCheck
{
public EmployeeCheck(Employee employee)
{
var owner = employee as Owner;
var statuts= owner.Status;
}
}
The first question you need to consider is: what is EmployeeCheck supposed to do when it is instantiated with an Employee (say) since it seems to require Status to print a check?
The whole idea behind interfaces is that they provide a contract for the operations that can be performed with an object. In this case, you are trying to do something (use Status) that is not specified in the contract so the type system is making it a little bit harder (forcing you to cast).
An option (as suggested by #Diegorincon) which avoids casting, is to create another interface (something like IHasStatus) which implements IEmployee and then change the type in EmployeeCheck (CheckPrinter maybe clearer?) to IEmployeeWithStatus.
interface IEmployee
{
string FirstName { get; }
string LastName { get; }
}
interface IEmployeeWithStatus:IEmployee
{
string Status { get; }
}
public class Owner : IEmployeeWithStatus
{
public string FirstName { get; }
public string LastName { get; }
public string Status { get; }
}
class EmployeeCheck
{
private readonly IEmployeeWithStatus _employeeWithStatus;
public EmployeeCheck(IEmployeeWithStatus employeeWithStatus)
{
_employeeWithStatus = employeeWithStatus;
}
void PrintCheck()
{
// no casting needed
Console.Write($"{_employeeWithStatus.FirstName} {_employeeWithStatus.LastName} {_employeeWithStatus.Status}");
}
}
If you are stuck using the signatures in your example, one option for writing the code is to write a switch statement using the type pattern:
switch (employee)
{
case Owner owner:
{
// you can use owner.Status here
Console.WriteLine(owner.Status);
}
break;
case Employee employee:
{
// hmm.., now what?!
}
break;
}
It's cleaner than having to cast all over the place but at the end of the day, it's just pushing the same problem around.
(In the Object Oriented paradigm, this situation comes up all the time where you have a object in hand with a more general type (something like Animal) but you find yourself wanting to do operations based on its specific type (something like Dog). Switching on type as the code above does is usually considered a code smell. With more details, I might be able to offer some other ideas)

How to get whole types that is used in a class with Roslyn? (all nested/inner types recursively)

Please consider this sample:
public class Person
{
public Guid Id { get; set; }
public string Name { get; set; }
public float Age { get; set; }
public List<Address> Addresses { get; set; }
public IEnumerable<Job> Jobs { get; set; }
public IInterface MyInterface { get; set; }
}
public class Address
{
public string City { get; set; }
public string[] Phones { get; set; }
public MyEnum E1 { get; set; }
}
public class Job
{
public Dictionary<decimal, Address> A1 { get; set; }
public Collection<DateTime> Date { get; set; }
public Tuple<double, BigInteger> A2 { get; set; }
}
public enum MyEnum
{
En1,
En2
}
As you see, I want to get all inner classes/structs/types of Person
so the result is :
Person.GetInnerTypes():
Guid
float
string
IInterface
Address
string[]
MyEnum
Job
List<Address>
IEnumerable<Job>
Dictionary<decimal, Address>
decimal
Collection<DateTime>
DateTime
Tuple<double, BigInteger>
double
BigInteger
The types are collected from everywhere (properties, arguments,...)
Is it possible to find whole types (recursively) by Roslyn?
Does anyone have an idea?
EDIT:
Why do I need this?
The problem comes from creating a code generator, if you see the Bogus library you should define rules for every type at first then create the main rule for Person class so I need to know all types for a class to create a code generator for generating test data! (generate a working class)
EDIT 2:
That's a very broad answer.
If you are interested in the properteis only - just use this question. Find your class' DeclarationSyntax, then find all DescendantNodes of PropertyDeclarationSyntax type. PropertyDeclarationSyntax will give you access to types, and you will go into recursion (don't forget about loops). This should be enough for a prototype.
Even on this step you should be careful with
Nested classes. Types used there will be included into your list too.
Generics. Sometime there are limitations like Type where T : ISomeInterface. Also, nested Generics.
Partial classes
Is Func < T1, T2> the same with Func< T2, T1> for you?
After all, there are questions about your problem itself.
Do you need parents of used types?
Do you care about properties only, or methods\fields\events etc are valuable also?
Should you think about properties inherited from the parents?
If you care about methods - should you think about parameters types?
If you care about methods - should you think about variables defined inside?
Edit1.
Maybe reflection is enough for your task?
static void Main(string[] args)
{
var properties = typeof(DemoPerson).GetProperties();
foreach(var property in properties)
{
Console.WriteLine($"Property: {property.Name}\tType: {property.PropertyType}");
}
Console.ReadLine();
}
public class DemoPerson
{
public Guid Id { get; set; }
public string Name { get; set; }
public List<DemoAddress> Addresses { get; set; }
}
public class DemoAddress
{
public string City { get; set; }
}
With output
Property: Id Type: System.Guid
Property: Name Type: System.String
Property: Addresses Type: System.Collections.Generic.List`1[DemoInnerTypes.Program+DemoAddress]

How to include properties via composition?

After having to refactor the inheritance chain in my current project for the third time I googled "Inheritance sucks" and found that the problem I'm having is not uncommon and composition is a recommended alternative solution.
I understand how you can use composition to add behavior in form of functions, but I'm having problems to come up with ways to add properties by the same means.
Let's say I want to model tree nodes. Every node has at least two properties: name and description.
class Node {
public string Name { get; set; }
public string Description { get; set; }
}
Other more specific nodes would inherit those properties, like so:
class StructuredNode : Node {
public List<Node> Children { get; set; }
}
How could I achieve similar re-usability of the property code without relying on inheritance and the problems that come with it?
Is there a design pattern for this or do I have to use inheritance in such a case?
Thanks in advance!
Edit:
Examples for the position "composition over inheritance":
ScottLilly
Wikipedia
Codingdelight
Rather then depending on class , you should depend son abstraction (this also one part of making use of composition) so for you case you should do like this
public interface INode {
string Name { get; set; }
string Description { get; set; }
}
class Node : INode {
public string Name { get; set; }
public string Description { get; set; }
}
class StructuredNode : INode {
public string Name { get; set; }
public string Description { get; set; }
public List<INode> Children { get; set; }
}
or you can also do this
//this is something similar to decorator pattern.
class StructuredNode {
private readonly INode _node;
public StructureNode(INode node)
{
_node = node;//now you can reuse function of any class which implements INode
}
public List<INode> Children { get; set; }
}
you should do like this also later on
List<Node> nodes = List<Node>();
StructuredNode sNode = new StructuredNode();
sNode.Children = nodes;
this is possible as all is based on abstraction. and all implementation now make use of INode
or
other solution suggested you in comment is make use of Decorator pattern. If you just want to extend you class without modifying it.
How could I archive similar re-usability of the property code without relying on inheritance and the problems that come with it?
The alternative to using inheritance is either interfaces or composition. However, for properties specifically, you're a bit stuck.
Interfaces cannot contain a default implementation the same way that a base class can. So while you can enforce that your classes use the correct "composed property structure", you can't make reusable methods available without implementing them in every class that implements the interface (or can you? More after the break!)
Composition simply doesn't exist in C# in a way that you can add properties to a class on the fly (unless you are satisfied with a Dictionary<string,string>). There may be some contrived method to technically make it work, but it won't be a good approach.
Interfaces + extension methods.
Extension methods can be used here to replace the reusable logic that you'd find in an inherited base class.
There is one drawback to this: The properties that you wish to access inside the extension methods need to be part of the interface contract and publically accessible.
Other than this drawback, it ticks the box on every other requirement you have.
First, an inheritance-based example:
public class Property
{
public string Name { get; set; }
public string Value { get; set; }
}
public class PropertyComposedObject
{
public List<Property> Properties { get; set; }
public Property GetProperty(string name)
{
return this.Properties.SingleOrDefault(x => x.Name == name);
}
}
public class Person : PropertyComposedObject
{
}
If we were to use an interface instead, we would lose access to benefits such as a shared GetNode(string) method. You could add it as part of the interface, but each implementing class would then be responsible for implementing that method (leading you to copy/paste the same methods all over the place).
An interface example without extension methods:
public class Property
{
public string Name { get; set; }
public string Value { get; set; }
}
public interface IPropertyComposedObject
{
List<Property> Properties { get; set; }
Property GetProperty(string name);
}
public class Person : IPropertyComposedObject
{
public List<Property> Properties { get; set; }
public Property GetProperty(string name)
{
return this.Properties.SingleOrDefault(x => x.Name == name);
}
}
But extension methods allows us to define the reusable method once but still access it from every class that implements the interface:
public class Property
{
public string Name { get; set; }
public string Value { get; set; }
}
public interface IPropertyComposedObject
{
List<Property> Properties { get; set; }
}
public class Person : IPropertyComposedObject
{
public List<Property> Properties { get; set; }
}
public static class IPropertyComposedObjectExtensions
{
public Property GetProperty(this IPropertyComposedObject obj, string name)
{
return obj.Properties.SingleOrDefault(x => x.Name == name);
}
}
My attempt to minimize code duplication:
interface INodeProperties
{
string Name { get; set; }
string Description { get; set; }
}
class NodeProperties : INodeProperties
{
public string Name { get; set; }
public string Description { get; set; }
}
interface INode
{
INodeProperties NodeProps { get; set; }
}
class Node : INode
{
public INodeProperties NodeProps { get; set; } = new NodeProperties();
}
interface IStructuredNode
{
List<Node> Children { get; set; }
}
class StructuredNode: INode, IStructuredNode
{
public INodeProperties NodeProps { get; set; } = new NodeProperties();
public List<Node> Children { get; set; }
}
Downside: One more "hop" to get to the actual Properties ... :(
Have an INode interface, which encapsulates common properties.
This way you should have auto properties, then avoid putting logic in properties' getter and setter, because you can not reuse this logic.
Then repeating auto property definitions is not important and does not affect reusability.
If you need property change notification, it is better to use interceptor libraries such as postsharp.

Lots of constructor parameters - Is there a better way?

public class HourlyForecastData
{
public DateTime DateTime { get; private set; }
public decimal TemperatureCelcius { get; private set; }
public decimal DewPoint { get; private set; }
public string Condition { get; private set; }
public int ConditionCode { get; private set; }
public int WindSpeed { get; private set; }
public string WindDirection { get; private set; }
public decimal WindDegrees { get; private set; }
public int UltravioletIndex { get; private set; }
public decimal Humidity { get; private set; }
public decimal WindChill { get; private set; }
public int HeatIndex { get; private set; }
public decimal FeelsLike { get; private set; }
public decimal Snow { get; private set; }
public HourlyForecastData(DateTime dateTime, decimal temperatureCelcius, ...)
{
DateTime = dateTime;
TemperatureCelcius = temperatureCelcius;
//...set all the other properties via constructor
}
}
I am trying to learn better software design and OOP. I'm creating a library that can access a weather service that replies with XML. There are a lot of different fields provided by the service, so I've created properties for each of the XML fields. However, it feels a bit messy to have that number of properties set via the constructor. I could omit the constructor and have public setters but I'm trying to make an immutable class.
I've looked around at different design patterns for this and there seems to be some "Builder" and "Factory" patterns. However, I'm struggling to understand how I would apply that to my code. Or should I be using something completely different to fill the properties in these objects?
In this case composition might be a good fit. Especially since there are some parameters that belongs to specific categories.
For instance:
public int WindSpeed;
public string WindDirection;
public decimal WindDegrees;
Create a new object for them and then access the different values as:
weatherData.Wind.Speed;
and pass the new wind object to the constructor:
var wind = new Wind(xmlData.WindSpeed, xmlData.WindDirection, xmldata.WindDegrees);
var weatherReport = new WeatherReport(wind, /* .... */);
I would also introduce a few enums. Because as of now, the users of the weatherReport would for instance have to know which values the string WindDirection can have. If you convert the string to an enum instead it's a lot easier to use the different values.
A final note is that I typically only use constructors if the are some values that really have to be specified for the class to have a valid state. For instance, in your case the minimum valid state would be a date and the temperature? Then just put those in the constructor.
Re Is there a better OOP approach?
A large number of properties on a class can often indicate a need for splitting the class up (the Single Responsibility Principle of SOLID).
e.g. It would appear that HourlyForecastData models Wind (speed and direction), Precipitation (Snow, Dew and Rain), and Temperature (Min, Max ...) These concerns can be split into separate classes, and then the HourlyForecastData would be a composition of the three.
Re : Builder Pattern
The Builder Pattern can be useful to ease the burden during construction of large (often immutable) classes or graphs, but would obviously require additional (mutable) Builder class(es) to build up the target class representation (i.e. HourlyForecastData) and eventually create it (viz, by constructing it immutably by passing it all parameters to the constructor). So it isn't less effort, if that is what you required by 'better', but this can certainly can be easier to read e.g.:
HourlyForecastData todaysForecast = new HourlyForecastDataBuilder()
.WithBaseline(ObjectMother.WinterSnow) // Provide an archetype
.WithPrecipitation(snow: 5, rain:1) // Dew defaults to 0
.Build();
Baseline archetypes / object mothers would be useful if the weather patterns in an area were frequently stable and just required small adjustments. IMO builder pattern is most useful in Testing. I can't see an obvious fit in an Xml Serialization usage.
See also Named and Optional parameters
Re: Immutability
A private setter technically still allows mutability, although restricted within the class itself. C#6 and later supports getter-only auto properties which is the simplest form for implementing immutable properties
public class HourlyForecastData
{
public DateTime DateTime { get; }
...
public HourlyForecastData(DateTime dateTime, ...)
{
// Get only auto properties can only be set at construction time
DateTime = dateTime;
...
Unrelated, but Scala offers an even more concise syntax than C# for defining immutable public properties on a class, by declaring them once in the (primary) constructor:
class HourlyForecastData(val temperature: Int, val station: String, ...) {
}
Without the need for any further property or backing fields, whilst expressing and enforcing immutability. However, the burden still remains on the caller to provide all the parameters (whether directly, or via Builder, etc).
Re : Xml
If you are offering an API, I would suggest using WebAPI. Instead of building Xml serialization concerns into your DTO classes, I would suggest instead on relying on Content Negotiation. This will allow the caller to determine whether the data should be returned in Xml or JSON format.
* Note however that Xml Deserialization technologies often make use of reflection to populate DTO properties, which MAY require that the serializable properties have setters (even if private).
One way is to use a struct and pass it in instead. It also makes using the class easier as you only need to declare the struct state variable, change whatever differs from the "default" then pass it in.
public struct HourlyForecastDataState
{
public DateTime DateTime;
public decimal TemperatureCelcius;
public decimal DewPoint;
public string Condition;
public int ConditionCode;
public int WindSpeed;
public string WindDirection;
public decimal WindDegrees;
public int UltravioletIndex;
public decimal Humidity;
public decimal WindChill;
public int HeatIndex;
public decimal FeelsLike;
public decimal Snow;
}
public class HourlyForecastData
{
public DateTime DateTime { get; private set; }
public decimal TemperatureCelcius { get; private set; }
public decimal DewPoint { get; private set; }
public string Condition { get; private set; }
public int ConditionCode { get; private set; }
public int WindSpeed { get; private set; }
public string WindDirection { get; private set; }
public decimal WindDegrees { get; private set; }
public int UltravioletIndex { get; private set; }
public decimal Humidity { get; private set; }
public decimal WindChill { get; private set; }
public int HeatIndex { get; private set; }
public decimal FeelsLike { get; private set; }
public decimal Snow { get; private set; }
public HourlyForecastData(HourlyForecastDataState state)
{
DateTime = state.dateTime;
TemperatureCelcius = state.temperatureCelcius;
//...etc
}
}
//Usage:
HourlyForecastDataState HFDstate = new HourlyForecastDataState();
HFDstate.temperatureCelcius = 100 //omg, it's hot!
HourlyForecastData HFD = new HourlyForecastData(HFDstate);

C#: interface inheritance getters/setters

I have a set of interfaces which are used in close conjunction with particular mutable object.
Many users of the object only need the ability to read values from the object, and then only a few properties. To avoid namespace pollution (easier intellisense) and to get across the usage intent, I'd like to have a small base interface which only exposes a few "key" properties in a read-only fashion.
However, almost all implementations will support the full interface, which includes modifiability.
Unfortunately, I ran into a roadblock expressing that concept in C#:
interface IBasicProps {
public int Priority { get; }
public string Name {get;}
//... whatever
}
interface IBasicPropsWriteable:IBasicProps {
public int Priority { set; } //warning CS0108: [...] hides inherited member [...]
public string Name { set; }
//... whatever
}
I certainly wasn't intending to hide any members, so that aint good!
Of course, I can solve this using methods just fine, but what's the right choice? I'd like to keep the "core" interface as small as possible even if splitting the interfaces serves no purpose other than communicating intent. With split interfaces, it's just really obvious which methods aren't going to do any updating, and it makes writing code a bit clearer (not to mention also allows nice-n-simple static singleton stubs that suffice for quite a few simple cases).
I'd like to avoid any abstract classes and the like; they make reimplementation or quick single-purpose shims all that more complex and hard-to-grok.
So, ideas?
Method hiding in an interface isn't nearly as grungy; I'd go with something like:
interface IBasicProps {
int Priority { get; }
string Name {get;}
//... whatever
}
interface IBasicPropsWriteable:IBasicProps {
new int Priority { get; set; }
new string Name { get; set; }
//... whatever
}
class Foo : IBasicPropsWriteable {
public int Priority {get;set;}
public string Name {get;set;}
/* optional
int IBasicProps.Priority {get {return Priority;}}
string IBasicProps.Name {get {return Name;}}
*/
}
If your goal is to make it clearer when reading vs. writing is allowed, then I would use separate getter and setter methods rather than properties.
interface IBasicProps {
int GetPriority();
string GetName();
//... whatever
}
interface IBasicPropsWriteable:IBasicProps {
void SetPriority(int priority);
void SetName(string name);
//... whatever
}
One way could be to simply skip the inheritance of the interfaces. Make one read-only interface and one write-only, and implement as necessary:
interface IBasicPropsReadable {
int Priority { get; }
string Name { get; }
}
interface IBasicPropsWriteable {
int Priority { set; }
string Name { set; }
}
class SomeClassReadWrite : IBasicPropsReadable, IBasicPropsWriteable {
int Priority { get; set; }
string Name { get; set; }
}
class SomeClassReadOnly : IBasicPropsReadable {
int Priority { get; }
string Name { get; }
}
You could leave the interfaces unrelated and simply have your class implement both interfaces. After all the interfaces are simply defining the contract and the contracts don't need to be related. It seems like it just an optimization for you when coding to have the writeable one derive from the other, so you only have to specify one interface.
public interface IBasicProps
{
int Priority { get; }
string Name {get;}
//... whatever
}
public interface IBasicPropsWriteable
{
int Priority { get; set; }
string Name { get; set; }
//... whatever
}
public class Foo : IBasicProps, IBasicPropsWriteable
{
public int Priority { get; set; }
public string Name { get; set; }
// whatever
}
If you really needed the optimization, you could create another interface that derives from both and have your classes implement that.
public interface IBasicPropsAll : IBasicProps, IBasicPropsWriteable { }
public class Foo : IBasicPropsAll
{
public int Priority { get; set; }
public string Name { get; set; }
// whatever
}

Categories