So i'm following a C# beginner tutorial at dotnetcademy.net and one of the exercises is to Implement an abstract class.
and the goals are:
1. Create a class named SpaceStation that is abstract
2. On that abstract class, add a abstract method called FireLaser
3. Create a derived class called DeathStar that implements the FireLaser method to write "Pew pew" to the Console followed by a new line.
the code that you start with is:
using System;
// Implement your classes here
public class Program
{
public static void Main()
{
}
}
so i wrote this but it says on return that "Since 'DeathStar.FireLaser()' returns void, a return keyword must not be followed by an object expression"
but i don't know what else to write, i've tried multiple other things
using System;
// Implement your classes here
public abstract class SpaceStation
{
public abstract void FireLaser();
}
public class DeathStar : SpaceStation
{
public override void FireLaser()
{
return Console.WriteLine("Pew pew");
}
}
public class Program
{
public static void Main()
{
}
}
So if anybody has a solution so i can reflect it on what i wrote that would be nice or if anybody can say what it should be instead.
Remove the return statement from the overridden FireLaser method:
public class DeathStar : SpaceStation
{
public override void FireLaser()
{
Console.WriteLine("Pew pew");
}
}
A method marked as void does not return anything. The return keyword is usually used to return a result from a method. Therefore it usually does not make sense in a void method. Removing the return keyword from your statement will resolve your compiler error.
public class DeathStar : SpaceStation
{
public override void FireLaser()
{
Console.WriteLine("Pew pew");
}
}
Note that the return keyword can be used in a void method to end the method. However, its usage is generally discouraged because it can result code that returns from multiple places and this can be confusing. When used in this manner, you still do not return an actual value. return would be the only part of the statement. Consider the following code:
public void ProcessSomeWork(SomeWork work)
{
if(work.IsCompleted)
{
return;
}
work.DoSomething();
DoSomethingElseToWork(work);
}
Related
So, Im studying Design Patterns, and Im studying the Template Method.
From how I understood it, It is a set of Methods (The skeleton) wrapped in a Method (Operation) on an Abstract Class (If done via heritage), where different Concrete Subclasses write their own implementation of those methods (Not all of them).
But I have a doubt, what happens if some, maybe 2 methods of the skeleton are not used by a certain concretion?, Here I have an example I made, which totally violates the SRP:
using System;
namespace TemplatePattern
{
public abstract class Coffee
{
public void MakeCoffee()
{
HeatWater();
PutCoffee();
if (HaveMilk())
{
PutMilk();
}
if (HaveGratedChocolate())
{
PutGratedChocolate();
}
PutSweetener();
ServeCoffee();
}
internal void HeatWater()
{
Console.WriteLine($"I heated the water");
}
internal void ServeCoffee()
{
Console.WriteLine($"Coffee Served");
}
internal void PutCoffee()
{
Console.WriteLine("I put 2 spoons of Coffee");
}
internal virtual void PutMilk() { }
internal virtual void PutGratedChocolate() { }
internal abstract void PutSweetener();
public virtual bool HaveMilk()
{
return false;
}
public virtual bool HaveGratedChocolate()
{
return false;
}
}
}
Concrete class SimpleCoffeeWithMilk:
using System;
namespace TemplatePattern
{
public class SimpleCoffeWithMilk : Coffee
{
public override bool HaveMilk()
{
return true;
}
internal override void PutSweetener()
{
Console.WriteLine($"I put 1 spoon of Sugar");
}
internal override void PutMilk()
{
Console.WriteLine($"I put 100Cc of Milk");
}
}
}
Another Concrete class:
using System;
namespace TemplatePattern
{
public class CoffeeWithChocolate : Coffee
{
public override bool HaveGratedChocolate()
{
return true;
}
internal override void PutGratedChocolate()
{
Console.WriteLine("Put Chocolate");
}
internal override void PutSweetener()
{
Console.WriteLine($"Put Sugar");
}
}
}
Main Entry Point:
using System;
namespace TemplatePattern
{
class Program
{
static void Main(string[] args)
{
SimpleCoffeWithMilk coffeWithMilk = new SimpleCoffeWithMilk();
CoffeeWithChocolate coffeeWithChocolate = new CoffeeWithChocolate();
coffeWithMilk.MakeCoffee();
Console.WriteLine("\n\n");
coffeeWithChocolate.MakeCoffee();
Console.ReadLine();
}
}
}
The idea is to get rid of those If's Statements, is there any way of doing this with the template method, where some of the methods execute depending of the concrete class?
I was thinking in creating interfaces like ICoffeeWithMilk with PutMilk() method on it and implement that interface on my SimpleCoffeeWithMilk concrete class, but watching the UMLs, the Template Method for what I saw does not rely on Interfaces.
Edit: Now that I think of it, I cant use an interface as, the template method relates to a set of ordered methods in the operation, so these methods are out of the operation.
Edit 2: Ok, I was thinking that PutMilk() and PutGratedChocolate() are Hook methods, maybe I can make them abstract methods and in the concrete classes dont put any implementation, not even the not implemented exception class. With this they can exists without any if statements in my Template Method. But I think, Im not sure this violates the Liskov Substitution Principle.
Edit 3: Well... I was thinking, again, and came to the conclusion that, if those methods are virtual and have no implementation on the abstract class, I shouldn't worry about asking, if the concrete class uses that method, then you write the algorithm, if you don't use it, then dont, and it will do nothing, it will go to the next step.
Just remove the if statements and let the concretions make the decision by implementing them, like so:
public abstract class Coffee
{
public void MakeCoffee()
{
PutMilk();
}
protected abstract void PutMilk();
}
public class SimpleCoffeWithMilk : Coffee
{
public override void PutMilk()
{
Console.WriteLine($"I put 100Cc of Milk");
}
}
public class SimpleCoffeNoMilk : Coffee
{
public override void PutMilk()
{
//no op
}
}
As to your concern with this solution, I don't think it violates Liskov. The LSP states that a subtype must be substitutable for any other inheritors of it's base class, which these cases are. You can call PutMilk for either, and they will put all of the milk that is appropriate to their specialization of the interface. None of that variation impacts the calling method. To be clear, you can contrive an example that would do that, but in this case you are not going to run into a problem there.
You can transfer the selection statement (if statement in this case) to your templates but cannot get rid of them if you need to check some condition. Weather you do it like this
public abstract class Coffee
{
public abstract bool HaveMilk();
public void MakeCoffee()
{
if (HaveMilk())
{
PutMilk();
}
}
}
public class SimpleCoffeWithMilk : Coffee
{
public bool HaveMilk()
{
return true;
}
public override void PutMilk()
{
Console.WriteLine($"I put 100Cc of Milk");
}
}
or like this
public abstract class Coffee
{
public void MakeCoffee()
{
PutMilk();
}
}
public class SimpleCoffeWithMilk : Coffee
{
public bool HaveMilk()
{
return true;
}
public override void PutMilk()
{
if (HaveMilk())
{
Console.WriteLine($"I put 100Cc of Milk");
}
}
}
I strongly believe the latter is what you are looking for.
I have an Interface:
public interface IMessager
{
void ShowMessage();
}
Is there any way to implement this interface using extension methods?
public static class Extensions
{
public static void ShowMessage(this MyClass e)
{
Console.WriteLine("Extension");
}
}
and a class that implement it:
public class MyClass:IMessager
{
public void ShowMessage()
{
ShowMessage(); // I expect that program write "Extension" in console
}
}
But when I run the program I get the System.StackOverflowException.
The code you posted is just a method calling itself recursively (hence the StackOverflowException).
I'm not entirely sure what you're trying to accomplish but to answer your question
Is there any way to implement this interface using extension methods?
No.
To be a bit more pragmatic about this though, if your aim is to only write your method once you have a few options:
1. Call the extension explicitly
public class MyClass:IMessager
{
public void ShowMessage()
{
Extensions.ShowMessage(this);
}
}
although as pointed out in comments, this basically defeats the point of using the extension method. Additionally there is still "boiler-plate code" such that every time you implement your interface you have to call the static method from within the method (not very DRY)
2. Use an abstract class instead of an interface
public abstract class MessengerBase
{
public void ShowMethod() { /* implement */ }
}
public class MyClass : MessengerBase {}
...
new MyClass().ShowMethod();
This issue with this though is that you can't inherit from multiple classes.
3. Use extension on the interface
public interface IMessenger { /* nothing special here */ }
public class MyClass : IMessenger { /* also nothing special */ }
public static class MessengerExtensions
{
public static void ShowMessage(this IMessenger messenger)
{
// implement
}
}
...
new MyClass().ShowMessage();
I would like to ask what are the risks of having something as follows:
abstract public class HtmlTemplateBuilder
{
HtmlSource source;
protected HtmlTemplateBuilder()
{
LoadTemplates();
}
public abstract void LoadTemplates();
}
The risk is if a derived class derives from the derived class:
DerivedClass2 -> #DerivedClass1 -> HtmlTemplateBuilder
This can be solved by sealing #DerviedClass1, but are there any more risks or better practices for implementing this functionality?
Thanks
The situation in which this pattern bit me is as follows: at some later stage you want to add a specialized HtmlTemplateBuilder, which can load different templates based on some criteria unknown to the class itself (maybe you decide you want some cool templates on a specific day of the year). That is:
public class SpecialHtmlTemplateBuilder : HtmlTemplateBuilder
{
private bool someCondition;
public override void LoadTemplates()
{
if (someCondition)
{
LoadTemplatesSet1();
}
else
{
LoadTemplatesSet2();
}
}
}
But how are you going to pass someCondition to the class? The following won't work:
public class SpecialHtmlTemplateBuilder : HtmlTemplateBuilder
{
private bool someCondition;
public SpecialHtmlTemplateBuilder (bool someCondition)
{
this.someCondition = someCondition;
}
// ...
}
because the assignment of this.someCondition will be done after calling the base constructor, i.e., after LoadTemplates() is called. Note that sealing derived classes does not solve this problem.
The way to solve this is as #Rahul Misra described: add an explicit Initialize method and call that after the constructor.
Have a look at this link which explains the perils with simple easy to understand examples
https://blogs.msmvps.com/peterritchie/2012/04/25/virtual-method-call-from-constructor-what-could-go-wrong/
I would remove the call to LoadTemplates from constructor and call Initialise on it when the templates actually need to be loaded and used.
abstract public class HtmlTemplateBuilder
{
HtmlSource source;
object locker = new object();
private bool initialised;
protected HtmlTemplateBuilder()
{
}
protected void Initialise()
{
lock (locker)
{
if(initialised)
{
LoadTemplates();
initialised = true;
}
}
}
public abstract void LoadTemplates();
}
I have a abstract class named Vehicle:
public abstract class Vehicle {
public void run() {
addToRunningVehicleList();
}
}
I want that every classes that extends Vehicle must call super.run() if they override run method. For example:
public class Car {
#Override
public void run() { // Error here because does not call super.run()
carRunningAnimation();
}
}
Is it possible in OOP concept, or Java/C#?
EDIT: Following Petar Ivanov, I have this code:
public abstract class Vehicle {
public final void run() {
Log.e("Run", "Add To List");
runImp();
}
public void runImp() {}
}
public class Car extends Vehicle {
#Override
public void runImp() {
Log.e("Run", "Run in Car");
}
}
However, it's not very good for public APIs. When extending Vehicle, the end-users must override runImp, but then they have to call run() method, so I have to make public both run and runImp, which make nothing better.
Here is how I would do it (C#):
public abstract class Vehicle {
public void Run() {
//code that will always run
addToRunningVehicleList();
//code that can be overriden
RunImpl();
}
protected virtual void RunImpl() { }
}
public class Car : Vehicle {
protected override void RunImpl() {
carRunningAnimation();
}
}
You can make the RunImpl protected to make sure it can't be called outside the subclasses of Vehicle.
If you need to require certain code to run in addition to the child class' implementation, perhaps you need to split this into multiple methods:
(C# example)
public abstract class Vehicle
{
public void Run()
{
// Code that always runs before...
RunCore();
// Code that always runs after...
}
protected virtual void RunCore()
{
}
}
Remember who you are designing for. If it's an internal piece of code a comment will suffice. If it's a public API and you want people to inherit then you need to write a piece of documentation telling them to do it.
In C# you can do some sneaky stuff with virtual and non-virtual methods but in Java as all inheritence is virtual it's a lot harder to enforce this without using an abstract base class.
Using an ABT may limit your ability to provide further inheritence and force modification of other code.
What I want to do is really simple. I have a class which handles my database executions called clsSQLInterface. This class contains a static function called bool isSQLSafe which will return false if the SQL being sent for execution is considered dangerous. This is so I have one point where I can filter out any malicious goings on.
Now, another part of my program actually needs to be able to do things like UPDATE, DELETE etc. So I thought I would inherit the clsSQLInterface class and override the isSQLSafe function with something that always returns true.
This isn't a question about database secutrity btw!
Ok so I did this like this...
public class clsSQLInterface //Code not shown, just definitions
{
private static string connectionString(string sKey){...}
public static bool isSQLSafe(string sSQL){...}
public static DataTable executeSQLText(string sSQL, string sConnectionKey){...}
public static DataTable executeGenericQuery(clsGenericSQL query,string sDBKey){...}
}
And the overriding class..
public class clsSQLInterface_unsafe : clsSQLInterface
{
public clsSQLInterface_unsafe()
{
}
public new static bool isSQLSafe(string sSQL) //overriding the base method
{ return true; }
}
Ok. The problem with this approach is that isSQLSafe is called from within the methods executeSQLText and executeGenericQuery. What I want these methods to do is call the overridden isSQLSafe which always returns true. However, they don't. They call the base implementation.
Do I also have to override every method which calls isSQLSafe? This seems like a waste of code.
Surely when I inherit the class I am effectively 'copying' all the base methods and they should behave as though they are now part of clsSQLInterface_unsafe?
You cannot override static methods. They are not inherited, they are methods of the class, not of an instance of the class. A static method in the base class will always call the static method in the same class.
Just making the methods not static and virtual, then overriding them in the derived class should solve your problem.
EDIT: the new static modifier just tells the compiler that you intend to hide the method of the base class (try to remove it and see the warning you get), but it does not override anything.
Overriding means that the derived class version of the function is taking the place of the base class version in the virtual table.
The virtual table is an index of the methods associated to an instance. No instance, no virtual table, therefore you cannot override a static method.
P.S: have a look at a better explaination of what is a virtual table here: http://en.wikipedia.org/wiki/Virtual_method_table
The problems comes from the static modifier.
You may reconsider refactor your code using, why not, something like this :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public abstract class BaseSqlInterface
{
protected abstract bool IsSafe(string instruction);
public void Execute(string sqlStatement)
{
if (IsSafe(sqlStatement))
{
// run the sql command
}
else
{
throw new Exception("You're evil");
}
}
}
public class SqlInterfaceSafe : BaseSqlInterface
{
public override bool IsSafe(string instruction)
{
return instruction.Contains("I'm not evil, I promise");
}
}
public class SqlInterfaceUnsafe : BaseSqlInterface
{
public override bool IsSafe(string instruction)
{
return true;
}
}
public static class SqlInterfaceFactory
{
public static BaseSqlInterface GetInstance()
{
// return the actual object using IOC, switch, ... whichever method you want
return DateTime.Now.Day % 2 == 0 ? (BaseSqlInterface)new SqlInterfaceSafe() : new SqlInterfaceUnsafe();
}
}
}