public static class or const - class

Should I rather create a public static class or use internal constants?
I am working on a very large application and noticed the use of const string at numerous places.This is used to compare the users selection
const string Thatch = "Thatch";
const string BrickAndTimberFrame= "Brick And Timber Frame";
const string OtherRoof = "Other";
etc......
etc......
What I want to do is to rather create public static class in the Core Application (see code below). The reason for this is that I only have to change/add a value at one place only.
public static class RoofConstruction
{
public static String Thatch{ get { return "Thatch"; } }
public static String BrickAndTimberFrame { get { return "Brick And Timber Frame"; } }
etc....
etc....
}
The compare function will then look like this
internal bool SlateTileOrConcreteRoof()
{
return RiskInformation.RoofConstruction.Value == RoofConstruction.Slate ||
RiskInformation.RoofConstruction == RoofConstruction.TileAndSlate ||
RiskInformation.RoofConstruction == RoofConstruction.Concrete;
}
Please add any comments/improvements etc

Generally speaking, I think that “the defining characteristic of ‘a Good Class™’,” is that “it does the right thing, nevermind(!) ‘how, exactly,” it does it.”
When you export constants from the class, this suggests that an unknown-number of other sections of the application (present and future ...) will contain logic that tests against that string.
Therefore, the question that only you can really answer: “do they really care about ‘the value of that string,’ or do they want ‘the answer to a yes-or-no question, which is answered in part based on the value of that string?’” This might guide your decision about what is best to do. (Mind you, I do not think that there is any sort of bright-line rule. I have done it both ways...)

Related

Class Design - Object Oriented Programming Question

This was asked during an interview.
There are different manufacturers of buses. Each bus has got different models and each model has only 2 variants. So different manufacturers have different models with only 2 variants. The interviewer asked me to design a standalone program with just classes. She mentioned that I should not think about databases and I didn't have to code them. For example, it could be a console based program with inputs and outputs.
The manufacturers, models and variants information should be held in memory (hard-coded values were fine for this standalone program). She wanted to observe the classes and my problem solving approach.
She told me to focus on implementing three APIs or methods for this system.
The first one was to get information about a particular bus. Input would be manufacturer name, model name and variant name. Given these three values, the information about a particular bus such as its price, model, year, etc should be shown to the client.
The second API would be to compare two buses and the output would be to list the features side by side, probably in a tabular format. Input would be the same as the one for the first API i.e. manufacturer name, model name and variant name for both the buses.
The third one would be to search the buses by price (>= price) and get the list of buses which satisfy the condition.
She also added that the APIs should be scalable and I should design the solution with this condition on my mind.
This is how I designed the classes:
class Manufacturer {
private String name;
private Set<Model> models;
// some more properties related to manufacturer
}
class Model {
private String name;
private Integer year;
private Set<Variant> variants;
// some more properties related to model
}
class Variant {
private String name;
private BigDecimal price;
// some more properties related to variant
}
class Bus {
private String manufacturerName;
private String modelName;
private String variantName;
private Integer year;
private BigDecimal price;
// some more additional properties as required by client
}
class BusService {
// The first method
public Bus getBusInformation(String manufacturerName, String modelName, String variantName) throws Exception {
Manufacturer manufacturer = findManufacturer(manufacturerName);
//if(manufacturer == null) throw a valid exception
Model model = findModel(manufacturer);
// if(model == null) throw a valid exception
Variant variant = findVariant(model);
// if(variant == null) throw a valid exception
return createBusInformation(manufacturer, model, variant);
}
}
She stressed that there were only 2 variants and there wouldn't be any more variants and it should be scalable. After going through the classes, she said she understood my approach and I didn't have to implement the other APIs/methods. I realized that she wasn't impressed with the way I designed them.
It would be helpful to understand the mistake I made so that I could learn from it.
I interpreted your 3 requirements a bit differently (and I may be wrong). But it sounds like the overall desire is to be able to perform different searches against all Models, correct?
Also, sounds to me that as all Variants are Models. I suspect different variants would have different options, but nothing to confirm that. If so, a variant is just a subclass of a particular model. However, if variants end up having the same set of properties, then variant isn't anything more than an additional descriptor to the model.
Anyway, going on my suspicions, I'd have made Model the center focus, and gone with:
(base class)
abstract class Model {
private Manufacturer manufacturer;
private String name;
private String variant;
private Integer year;
private BigDecimal price;
// some more properties related to model
}
(manufacturer variants)
abstract class AlphaModel {
AlphaModel() {
this.manufacturer = new Manufacturer() { name = "Alpha" }
}
// some more properties related to this manufacturer
}
abstract class BetaModel {
BetaModel() {
this.manufacturer = new Manufacturer() { name = "Beta" }
}
// some more properties related to this manufacturer
}
(model variants)
abstract class AlphaBus : AlphaModel {
AlphaBus() {
this.name = "Super Bus";
}
// some more properties related to this model
}
abstract class BetaTruck : BetaModel {
BetaTruck() {
this.name = "Big Truck";
}
// some more properties related to this model
}
(actual instances)
class AlphaBusX : AlphaBus {
AlphaBusX() {
this.variant = "X Edition";
}
// some more properties exclusive to this variant
}
class AlphaBusY : AlphaBus {
AlphaBusY() {
this.variant = "Y Edition";
}
// some more properties exclusive to this variant
}
class BetaTruckF1 : BetaTruck {
BetaTruckF1() {
this.variant = "Model F1";
}
// some more properties exclusive to this variant
}
class BetaTruckF2 : BetaTruck {
BetaTruckF2() {
this.variant = "Model F2";
}
// some more properties exclusive to this variant
}
Then finally:
var data = new Set<Model> {
new AlphaBusX(),
new AlphaBusY(),
new BetaTruckF1(),
new BetaTruckF2()
}
API #1:
var result = data.First(x => x.manufacturer.name = <manufactuer>
&& x.name = <model>
&& x.variant = <variant>);
API #2:
var result1 = API#1(<manufacturer1>, <model1>, <variant1>);
var result2 = API#1(<manufacturer2>, <model2>, <variant2>);
API #3:
var result = data.Where(x => x.price >= <price>);
I would say your representation of the Bus class is severely limited, Variant, Model, Manufacturer should be hard links to the classes and not strings. Then a get for the name of each.
E.G from the perspective of Bus bus1 this.variant.GetName() or from the outside world. bus1.GetVariant().name
By limiting your bus to strings of it's held pieces, you're forced to do a lookup even when inside the bus class, which performs much slower at scale than a simple memory reference.
In terms of your API (while I don't have an example), your one way to get bus info is limited. If the makeup of the bus changes (variant changes, new component classes are introduced), it requires a decent rewrite of that function, and if other functions are written similarly then all of those two.
It would require some thought but a generic approach to this that can dynamically grab the info based on the input makes it easier to add/remove component pieces later on. This will be the are your interviewer was focusing on most in terms of advanced technical&language skills. Implementing generics, delegates, etc. here in the right way can make future upkeep of your API a lot easier. (Sorry I don't have an example)
I wouldn't say your approach here is necessarily bad though, the string member variables are probably the only major issue.

string hints in different languages

I am creating a game in Unity3d.
Somewhere I have hints appearing in the bottom of the HUD (Something like "press A for Action"). I want my game to support more languages and I don't want these hints to be hard-coded in the script.
What is the most elegant way to solve this task? I am thinking about txt file, where I will have all my hints in all languages. But I am not sure, if it is a good idea.
Thanks in advance.
A common way that is used is to have an XML-file for each language. The XML-file should contain every phrase you use in your game with a unique ID.
In your code, you can then get the correct phrase out of the current language's XML, using the correct ID.
If you don't know about XML files, read this tutorial about using XML files in Unity: http://xeophin.net/en/blog/2010/05/13/reading-strings-out-xml-file-using-c-unity-3d
However if you are willing to spend some money on your game, you should check this out: http://u3d.as/content/rodrigo-barros/my-menu/32E
I haven't tried that yet but it seems good.
Hardcoding is not that bad if you do it correctly.
For example create an abstract class with all the messages that you want to have and language autodetection:
public abstract class Lang {
static Lang currentLang;
public static Lang Get {
get {
if(currentLang == null)
switch(Application.systemLanguage) {
case SystemLanguage.Polish:
currentLang=new LangPL();
break;
default:
case SystemLanguage.English:
currentLang=new LangEN();
break;
}
return currentLang;
}
}
public abstract string MenuTime {get;}
public abstract string MenuPoints {get;}
public abstract string YouWon {get;}
public abstract string YouLost {get;}
public abstract string Point(int p);
}
And then implement each language as a separate class:
public class LangPL:Lang {
public override string MenuTime {get {return "CZAS";}}
public override string MenuPoints {get {return "WYNIK";}}
public override string YouWon {get {return "Gratuluję, wygrałeś!";}}
public override string YouLost{get {return "Może następnym razem...";}}
public override string Point(int p) {
if(p == 1)
return "1 punkt";
return p+" punktów";
}
}
public class LangEN:Lang {
public override string MenuTime {get {return "TIME";}}
public override string MenuPoints {get {return "SCORE";}}
public override string YouWon {get {return "You won!";}}
public override string YouLost{get {return "Maybe next time...";}}
public override string Point(int p) {
if(p == 1)
return "1 point";
return p+" points";
}
}
Usage is a simple:
GUILayout.Label(Lang.Get.YouWon);
GUILayout.Label(Lang.Get.Point(5));
This way you have most control, and can easily support complex translations. Also this approach helps to trim down on errors - if you forget or misstype a text anywhere it throws a syntax error.
You can try to create a Javascript script or a C# script for each language and then depending of the language choosen, you call the specific script.
e.g
public class English : MonoBehaviour{
public string jump = "Press 'space' to jump";
//etc
}
public class French : MonoBehaviour{
public string jump = "Appuyer sur 'espace' pour sauter";
//etc
}
In your function for GUIText
public GameController gameController;
public GUIText text;
private string languageSelected;// obtain from the user input on language selection (better if registered in the gameController)
void Awake(){
languageSelected = System.Activator.CreateInstance(Type.GetType(gameController.languageSelected));
// where languageSelected will be e.g English
text.text = languageSelected.jump;
}
I strongly advise against embedding text into your code. It will slow down the localization process (having to look through code to find text is not the quickest and best way to approach localization).
Go with separate files. It's easier to maintain and translators don't have to access the code.
Have a look at l2 localization. It's a pretty handy Unity plugin that allows you to manage translations of your game.
All your localized strings in a single Google Spreadsheet. Once set up, all you need to do is fill it out to see the results in the game.
I am a game translator myself and happen to be managing a small team of game translators called Level Up Translation. We posted a beginner's guide for localization in Unity in our blog a couple of months ago. Feel free to check it out!
For example, you can save language file for france.txt in format:
hello=Bonjour
goodbye=Au Revoir
And than, read file and convert it to dictionary:
string[] lines = File.ReadAllLines("france.txt");
var dict = lines.Select(l => l.Split('=')).ToDictionary(a => a[0], a => a[1]);
Now you can read from dictionary by key:
string hello = dict["hello"];

How do you refactor a God class?

Does anyone know the best way to refactor a God-object?
Its not as simple as breaking it into a number of smaller classes, because there is a high method coupling. If I pull out one method, i usually end up pulling every other method out.
It's like Jenga. You will need patience and a steady hand, otherwise you have to recreate everything from scratch. Which is not bad, per se - sometimes one needs to throw away code.
Other advice:
Think before pulling out methods: on what data does this method operate? What responsibility does it have?
Try to maintain the interface of the god class at first and delegate calls to the new extracted classes. In the end the god class should be a pure facade without own logic. Then you can keep it for convenience or throw it away and start to use the new classes only
Unit Tests help: write tests for each method before extracting it to assure you don't break functionality
I assume "God Object" means a huge class (measured in lines of code).
The basic idea is to extract parts of its functions into other classes.
In order to find those you can look for
fields/parameters that often get used together. They might move together into a new class
methods (or parts of methods) that use only a small subset of the fields in the class, the might move into a class containing just those field.
primitive types (int, String, boolean). They often are really value objects before their coming out. Once they are value object, they often attract methods.
look at the usage of the god object. Are there different methods used by different clients? Those might go in separate interfaces. Those intefaces might in turn have separate implementations.
For actually doing these changes you should have some infrastructure and tools at your command:
Tests: Have a (possibly generated) exhaustive set of tests ready that you can run often. Be extremely careful with changes you do without tests. I do those, but limit them to things like extract method, which I can do completely with a single IDE action.
Version Control: You want to have a version control that allows you to commit every 2 minutes, without really slowing you down. SVN doesn't really work. Git does.
Mikado Method: The idea of the Mikado Method is to try a change. If it works great. If not take note what is breaking, add them as dependency to the change you started with. Rollback you changes. In the resulting graph, repeat the process with a node that has no dependencies yet. http://mikadomethod.wordpress.com/book/
According to the book "Object Oriented Metrics in Practice" by Lanza and Marinescu, The God Class design flaw refers to classes that tend to centralize the intelligence of the system. A God Class performs too much work on its own, delegating only minor details to a set of trivial classes and using the data from other classes.
The detection of a God Class is based on three main characteristics:
They heavily access data of other simpler classes, either directly or using accessor methods.
They are large and complex
They have a lot of non-communicative behavior i.e., there is a low
cohesion between the methods belonging to that class.
Refactoring a God Class is a complex task, as this disharmony is often a cumulative effect of other disharmonies that occur at the method level. Therefore, performing such a refactoring requires additional and more fine-grained information about the methods of the class, and sometimes even about its inheritance context. A first approach is to identify clusters of methods and attributes that are tied together and to extract these islands into separate classes.
Split Up God Class method from the book "Object-Oriented Reengineering Patterns" proposes to incrementally redistribute the responsibilities of the God Class either to its collaborating classes or to new classes that are pulled out of the God Class.
The book "Working Effectively with Legacy Code" presents some techniques such as Sprout Method, Sprout Class, Wrap Method to be able to test the legacy systems that can be used to support the refactoring of God Classes.
What I would do, is to sub-group methods in the God Class which utilize the same class properties as inputs or outputs. After that, I would split the class into sub-classes, where each sub-class will hold the methods in a sub-group, and the properties which these methods utilize.
That way, each new class will be smaller and more coherent (meaning that all their methods will work on similar class properties). Moreover, there will be less dependency for each new class we generated. After that, we can further reduce those dependencies since we can now understand the code better.
In general, I would say that there are a couple of different methods according to the situation at hand. As an example, let's say that you have a god class named "LoginManager" that validates user information, updates "OnlineUserService" so the user is added to the online user list, and returns login-specific data (such as Welcome screen and one time offers)to the client.
So your class will look something like this:
import java.util.ArrayList;
import java.util.List;
public class LoginManager {
public void handleLogin(String hashedUserId, String hashedUserPassword){
String userId = decryptHashedString(hashedUserId);
String userPassword = decryptHashedString(hashedUserPassword);
if(!validateUser(userId, userPassword)){ return; }
updateOnlineUserService(userId);
sendCustomizedLoginMessage(userId);
sendOneTimeOffer(userId);
}
public String decryptHashedString(String hashedString){
String userId = "";
//TODO Decrypt hashed string for 150 lines of code...
return userId;
}
public boolean validateUser(String userId, String userPassword){
//validate for 100 lines of code...
List<String> userIdList = getUserIdList();
if(!isUserIdValid(userId,userIdList)){return false;}
if(!isPasswordCorrect(userId,userPassword)){return false;}
return true;
}
private List<String> getUserIdList() {
List<String> userIdList = new ArrayList<>();
//TODO: Add implementation details
return userIdList;
}
private boolean isPasswordCorrect(String userId, String userPassword) {
boolean isValidated = false;
//TODO: Add implementation details
return isValidated;
}
private boolean isUserIdValid(String userId, List<String> userIdList) {
boolean isValidated = false;
//TODO: Add implementation details
return isValidated;
}
public void updateOnlineUserService(String userId){
//TODO updateOnlineUserService for 100 lines of code...
}
public void sendCustomizedLoginMessage(String userId){
//TODO sendCustomizedLoginMessage for 50 lines of code...
}
public void sendOneTimeOffer(String userId){
//TODO sendOneTimeOffer for 100 lines of code...
}}
Now we can see that this class will be huge and complex. It is not a God class by book definition yet, since class fields are commonly used among methods now. But for the sake of argument, we can treat it as a God class and start refactoring.
One of the solutions is to create separate small classes which are used as members in the main class. Another thing you could add, could be separating different behaviors in different interfaces and their respective classes. Hide implementation details in classes by making those methods "private". And use those interfaces in the main class to do its bidding.
So at the end, RefactoredLoginManager will look like this:
public class RefactoredLoginManager {
IDecryptHandler decryptHandler;
IValidateHandler validateHandler;
IOnlineUserServiceNotifier onlineUserServiceNotifier;
IClientDataSender clientDataSender;
public void handleLogin(String hashedUserId, String hashedUserPassword){
String userId = decryptHandler.decryptHashedString(hashedUserId);
String userPassword = decryptHandler.decryptHashedString(hashedUserPassword);
if(!validateHandler.validateUser(userId, userPassword)){ return; }
onlineUserServiceNotifier.updateOnlineUserService(userId);
clientDataSender.sendCustomizedLoginMessage(userId);
clientDataSender.sendOneTimeOffer(userId);
}
}
DecryptHandler:
public class DecryptHandler implements IDecryptHandler {
public String decryptHashedString(String hashedString){
String userId = "";
//TODO Decrypt hashed string for 150 lines of code...
return userId;
}
}
public interface IDecryptHandler {
String decryptHashedString(String hashedString);
}
ValidateHandler:
public class ValidateHandler implements IValidateHandler {
public boolean validateUser(String userId, String userPassword){
//validate for 100 lines of code...
List<String> userIdList = getUserIdList();
if(!isUserIdValid(userId,userIdList)){return false;}
if(!isPasswordCorrect(userId,userPassword)){return false;}
return true;
}
private List<String> getUserIdList() {
List<String> userIdList = new ArrayList<>();
//TODO: Add implementation details
return userIdList;
}
private boolean isPasswordCorrect(String userId, String userPassword)
{
boolean isValidated = false;
//TODO: Add implementation details
return isValidated;
}
private boolean isUserIdValid(String userId, List<String> userIdList)
{
boolean isValidated = false;
//TODO: Add implementation details
return isValidated;
}
}
Important thing to note here is that the interfaces () only has to include the methods used by other classes. So IValidateHandler looks as simple as this:
public interface IValidateHandler {
boolean validateUser(String userId, String userPassword);
}
OnlineUserServiceNotifier:
public class OnlineUserServiceNotifier implements
IOnlineUserServiceNotifier {
public void updateOnlineUserService(String userId){
//TODO updateOnlineUserService for 100 lines of code...
}
}
public interface IOnlineUserServiceNotifier {
void updateOnlineUserService(String userId);
}
ClientDataSender:
public class ClientDataSender implements IClientDataSender {
public void sendCustomizedLoginMessage(String userId){
//TODO sendCustomizedLoginMessage for 50 lines of code...
}
public void sendOneTimeOffer(String userId){
//TODO sendOneTimeOffer for 100 lines of code...
}
}
Since both methods are accessed in LoginHandler, interface has to include both methods:
public interface IClientDataSender {
void sendCustomizedLoginMessage(String userId);
void sendOneTimeOffer(String userId);
}
There are really two topics here:
Given a God class, how its members be rationally partitioned into subsets? The fundamental idea is to group elements by conceptual coherency (often indicated by frequent co-usage in client modules) and by forced dependencies. Obviously the details of this are specific to the system being refactored. The outcome is a desired partition (set of groups) of God class elements.
Given a desired partition, actually making the change. This is difficult if the code base has any scale. Doing this manually, you are almost forced to retain the God class while you modify its accessors to instead call new classes formed from the partitions. And of course you need to test, test, test because it is easy to make a mistake when manually making these changes. When all accesses to the God class are gone, you can finally remove it. This sounds great in theory but it takes a long time in practice if you are facing thousands of compilation units, and you have to get the team members to stop adding accesses to the God interface while you do this. One can, however, apply automated refactoring tools to implement this; with such a tool you specify the partition to the tool and it then modifies the code base in a reliable way. Our DMS can implement this Refactoring C++ God Classes and has been used to make such changes across systems with 3,000 compilation units.

Proper place for human-readable representation of entity-based key

First some background. We recently converted from a Zend_Db_Table-based solution to entity-based solution (Doctrine). As our application grew, the table classes grew uglier and uglier. Some of the tables used ENUM columns to store string-based keys, which were converted into human-readable strings with static methods. Something like this:
public static function getProductType($productKey)
{
if (!array_key_exists($productKey, self::$productTypes)) {
return null;
}
return self::$productTypes[$productKey];
}
public static function getProductTypes()
{
return self::$productTypes;
}
In moving to the entity-based system, I tried to avoid static methods where possible. I moved the key to value translations into a view helper and called it a day. In the end, I found that it was not sufficient, as we needed to return them in JSON objects, which occurred outside of the presentation layer (i.e. no direct access to view helpers).
Does anyone have any theories on the proper place for these types of methods? Should I create separate objects for doing the translation from key to human-readable value, implement static methods on the entity object, or something else?
Well my theory is that this should be done in the model itself. But sometimes when dealing with a complex model, I like to create a separate class that handles any special "presentation" of that model. It takes the model as an argument and encapsulates the presentation logic.
So using your example, perhaps something like this:
class Model_Product
{
public static function getAllTypes()
{
return array(/* key-value pairs */);
}
//returns non human readable value
public function getType()
{
return $this->_type;
}
}
class Model_Product_Presenter
{
protected $_model;
public function __construct(Model_Product $model)
{
$this->_model = $model;
}
//returns human readable value
public function getType()
{
$types = $this->_model->getAllTypes();
if (!array_key_exists($this->_model->type, $types)) {
return null;
}
return $types[$this->_model->type];
}
public function getDateCreated($format = "Y-m-d")
{
return date($format,$this->_model->timestamp);
}
}
You can go further and create a base presenter class to define any common tasks, i.e. converting timestamps to dates, formatting numbers, etc.
Update:
For anonymous access to a list of product types, I don't see any harm in making it the responsibility of the product model via a static method. Not all static methods are evil. In my opinion, the use of static methods for this purpose is fine, because it declares a global constant.
In a more complex scenario, I would delegate this responsibility to a separate class like Model_ProductType. Here is an example of such a complex model in production:
https://github.com/magento/magento2/blob/master/app/code/core/Mage/Catalog/Model/Product/Type.php

Reading integers from AppSettings over and over

Some I do quite a lot of is read integers from AppSettings. What's the best way to do this?
Rather than do this every time:
int page_size;
if (int.TryParse( ConfigurationManager.AppSettings["PAGE_SIZE"], out page_size){
}
I'm thinking a method in my Helpers class like this:
int GetSettingInt(string key) {
int i;
return int.TryParse(ConfigurationManager.AppSettings[key], out i) ? i : -1;
}
but this is just to save some keystrokes.
Ideally, I'd love to put them all into some kind of structure that I could use intellisense with so I don't end up with run-time errors, but I don't know how I'd approach this... or if this is even possible.
What's a best practices way of getting and reading integers from the AppSettings section of the Web.Config?
ONE MORE THING...
wouldn't it be a good idea to set this as readonly?
readonly int pageSize = Helpers.GetSettingInt("PAGE_SIZE") doesn't seem to work.
I've found an answer to my problem. It involves extra work at first, but in the end, it will reduce errors.
It is found at Scott Allen's blog OdeToCode and here's my implementation:
Create a static class called Config
public static class Config {
public static int PageSize {
get { return int.Parse(ConfigurationManager.AppSettings["PAGE_SIZE"]); }
}
public static int HighlightedProductId {
get {
return int.Parse(ConfigurationManager.AppSettings["HIGHLIGHT_PID"]);
}
}
}
Advantage of doing this are three-fold:
Intellisense
One breakpoint (DRY)
Since I only am writing the Config String ONCE, I do a regular int.Parse.
If someone changes the AppSetting Key, it will break, but I can handle that, as those values aren't changed and the performance is better than a TryParse and it can be fixed in one location.
The solution is so simple... I don't know why I didn't think of it before. Call the values like so:
Config.PageSize
Config.HighlightedProductId
Yay!
I know that this question was asked many years ago, but maybe this answer could be useful for someone. Currently, if you're already receiving an IConfiguration reference in your class constructor, the best way to do it is using GetValue<int>("appsettings-key-goes-here"):
public class MyClass
{
private readonly IConfiguration _configuration;
public MyClass(IConfiguration configuration)
{
_configuration = configuration;
}
public void MyMethod()
{
int value = _configuration.GetValue<int>("appsettings-key-goes-here");
}
}
Take a look at T4Config. I will generate an interface and concrete implementation of your appsettings and connectionstringsections of you web/app config using Lazyloading of the values in the proper data types. It uses a simple T4 template to auto generate things for you.
To avoid creating a bicycle class you could use the following:
System.Configuration.Abstractions.AppSettings.AppSetting<int>("intKey");
https://github.com/davidwhitney/System.Configuration.Abstractions